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?
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'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With