I’m fairly new to RequireJS and I’ve run into a bit of a problem. I’ve written a little framework built on Backbone using RequireJS and I want it to be re-usable in different projects. So, with some searching I learned that require allows packages. This seemed like what I was looking for. I have a main.js file to launch my app that essentially looks like this:
require.config({
packages: ['framework']
});
require(['framework'], function(framework) {
framework.createDash();
});
Then in the same directory as my main.js I have another directory called “framework” which contains another main.js which looks like this:
define(function(require, exports, module) {
exports.createDash = function(dash, element) {
require(['dash/dash.model', 'dash/dash.view'], function(DashModel, DashView) {
return new DashView({
model: new DashModel(dash),
el: element ? element : window
});
});
};
});
In searching I found this page which indicates that the ‘require’ argument should be scoped to the submodule. However, when I try to require things they are still relative to my original main.js. I’ve tried a number of things and searched for hours to no avail. Is there any way I can have my require/define calls within my package included relative to the main.js in it’s root?
You need to define your submodule as package in the require configuration:
To load your module you just need to use your ‘packagename’ at the requirements:
In your package you must use the
./prefix to load your files relative to your submodule:There is a useful shortcut: If your package name equals to your location and your main file is called ‘main.js’, then you can replace this
to this:
As far as I can see, you already tried to define a package but did you also use the ./ prefix? Without this prefix require will try to find the files in it’s global root-path. And without a package,
./will be useless because the relative path is the same as the global root-path.Cheers