Search code examples
javascriptrequirejsamd

How to use only one RequireJS config file for different path js file?


I am integrating RequireJS into my project. My project structure like below:

$ tree
.
|-- common.js
|-- lib
|   |-- jquery.min.js
|   `-- require.js
`-- view
    |-- a
    |   |-- a.html
    |   |-- a.js
    |   `-- b
    |       |-- b.html
    |       `-- b.js
    |-- c.html   
    `-- c.js

common.js is my RequireJS config file, content like below:

requirejs.config({
    baseUrl: '../lib',
    paths: {
        'jquery': 'jquery.min'
    }
});

There are js files in different path in /view.

c.js running well as below:

requirejs(['../common'], function (common) {
    requirejs(['jquery'], function($){
    .......
    });
});

But how can I inject 'jquery' in a.js or b.js and still use common.js?


Solution

  • Don't forget to change the path to common.js. It should be:

    requirejs(['../../common'], function (common) { ... });
    

    from a.js and

    requirejs(['../../../common'], function (common) { ... });
    

    from b.js, since paths are relative to the current file.

    Alternatively, use an absolute path. That way the path is the same no matter which file you're requirejsing from. For example, if common.js is at http://www.example.com/scripts/common.js, use

    requirejs(['/common'], function (common) { ... });
    

    . (The leading / makes it an absolute path.)