2

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?

wannabeartist
  • 2,753
  • 6
  • 36
  • 49

2 Answers2

10

This code worked for me:

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

require(['OpenLayers'], function(OpenLayers) {
    console.log(OpenLayers);
});
Werner Kvalem Vesterås
  • 10,226
  • 5
  • 43
  • 50
  • Thank you, that works! However, I'd still like to know why is that required. I though shim was used for libraries that needed other dependencies, but OpenLayers needs none. – wannabeartist Oct 11 '12 at 14:32
  • 1
    I have no idea. I am pretty new to require.js. But it would be nice to know, so I will investigate further. – Werner Kvalem Vesterås Oct 11 '12 at 14:34
  • I have no idea why, but the OpenLayers.js library attaches itself to the global namespace, both with and without the shim config. With shim config. – Werner Kvalem Vesterås Oct 11 '12 at 15:12
  • 1
    See this for a possible explanation: http://stackoverflow.com/questions/12121367/requirejs-jquery-is-undefined-when-certain-alias-is-given – Deepak Joy Cheenath Aug 29 '13 at 16:35
  • worked for me when downloading the Openlayers zip package. Did someone manage to get it working with bower as well?? Should be the same, but didn't find an OpenLayers.debug.js there... – Juri Feb 24 '14 at 22:53
  • An explanation: [Requirejs why and when to use shim config](https://stackoverflow.com/a/28096524/2279924) – Patrick Dec 13 '17 at 10:33
6

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'
        }
mnoble01
  • 579
  • 5
  • 16