RequireJS: Why do relative paths work for define () but don't require ()?

Say you have the following directory structure and the following files:

root |-- require-jquery.js +-- folder |-- index.html |-- main.js +-- AnotherModule.js 

In RequireJS, when you refer to a module starting with ".", RequireJS looks in the same folder as your current module, even if it is a subdirectory. However, if you change baseUrl just before calling define (), RequireJS will map the dependencies to the new baseUrl.

You can fix this by setting baseUrl in index.html and changing the main data file to a path relative to baseUrl:

folder / index.html

 <script> var require = { baseUrl : "../" }; </script> <script data-main="folder/main" src="../require-jquery.js"></script> 

folder / main.js:

 define( [ "jquery", './AnotherModule' ], function($, AnotherModule) {}); 

This only works for define ():

folder / main.js:

 require( [ "jquery", './AnotherModule' ], function($, AnotherModule) {}); 

if I try with require (), RequireJS will look for AnotherModule.js in the root and not in the folder. Why is this and, in particular, why is there a design difference between define () and require ()?

+4
requirejs
Apr 18 '13 at 15:53
source share
1 answer

This is because define sets the module name and does not require it.

You can define it like this:

 define('folder/main', [ "jquery", './AnotherModule' ], function($, AnotherModule) {}); 

The first parameter is the name of the module — the explicit path to the module. Define () always implicitly specifies a path, and in general, using an explicit path is not recommended . The request does not accept the name parameter.

When you include a relative dependency in define () (for example, "./AnotherModule"), it was relative to the module name. In this case. / AnotherModule will allow the / AnotherModule folder.

The require () call does not have a module name. Relative dependencies are allowed for the root.

+7
Apr 24 '13 at 15:44
source share



All Articles