Reputation: 6806
I am trying to load a module using require.js, and I have the following in my app.js:
require.config({
baseUrl: "js"
});
alert("hello world"); // for debugging
require(['eh2'], function(eh2) {
alert("nothing here"); // for debugging
});
When I run my application, though, despite the app.js being loaded, the module I'm requiring is never loaded - the "hello world" executes, but the "nothing here" doesn't!
My script tag in the HTML page looks like this:
<script type="text/javascript" src="js/lib/require.js" data-main="app"></script>
And eh2.js is located in the js folder, and it is wrapped in a define statement:
define(["./screens/Screens"], function(screens) {
return {
// code here
};
});
What am I doing wrong? Is require.js silently failing on loading some submodule under screens.js, perhaps?
Here is the code from the Screens module:
define([ "screens/TitleScreen", "screens/GameScreen" ], function(titleScreen, gameScreen) {
return {
screenFuncs: {
"TitleScreen" : titleScreen.TitleScreen,
"GameScreen" : gameScreen.GameScreen,
},
buildScreen: function(data) {
var func = screenFuncs[data.type];
var screen = new func(data.params);
return screen;
},
};
});
Do the paths in the define call need to be relative to the current location of the js file I'm in, or to the root defined in the app.js, anyway?
Upvotes: 6
Views: 12874
Reputation: 2625
replace this:
define(["./screens/Screens"], function(screens) {
....
});
either with an absolut path variant:
define(["screens/Screens"], function(screens) {
....
});
or use:
define(function(require) {
var screens = require("./screens/Screens");
....
});
From the docs:
Relative module names inside define():
For require("./relative/name") calls that can happen inside a define() function call, be sure to ask for "require" as a dependency, so that the relative name is resolved correctly:
define(["require", "./relative/name"], function(require) {
var mod = require("./relative/name");
});
Or better yet, use the shortened syntax that is available for use with translating CommonJS modules:
define(function(require) {
var mod = require("./relative/name");
});
Upvotes: 5