Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency is undefined - RequireJS

Tags:

requirejs

I'm trying to use OpenLayers library with RequireJS.

The problem is, OpenLayers keeps being "undefined" even though it's listed as the only dependency for my module:

define(['OpenLayers'],function (OpenLayers) {
   console.log(OpenLayers);
});

this will print "undefined".

If I substitute the OpenLayers with jquery (both .js files are in the same folder), it will not be undefined any more.

So why is OpenLayers not loaded by RequireJS?

like image 878
wannabeartist Avatar asked Jul 16 '26 01:07

wannabeartist


2 Answers

This code worked for me:

require.config({
    shim: {
        OpenLayers: {
            exports: 'OpenLayers'
        }
    }
});

require(['OpenLayers'], function(OpenLayers) {
    console.log(OpenLayers);
});

I had this same problem with Backbone.Marionette. Adding 'marionette': { exports: 'Marionette' } to the shim object worked.

This shim addition works with both OpenLayers and Marionette for the following reason (from the RequireJS documentation):

shim: Configure the dependencies and exports for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. Example (RequireJS 2.1.0+):

requirejs.config({
    shim: {
        'backbone': {
            //These script dependencies should be loaded before loading
            //backbone.js
            deps: ['underscore', 'jquery'],
            //Once loaded, use the global 'Backbone' as the
            //module value.
            exports: 'Backbone'
        }
like image 33
mnoble01 Avatar answered Jul 19 '26 14:07

mnoble01