简体   繁体   中英

Require.js - loading modules relative to the root of the server

Imagine you have a large web application and you decide to use the require.js for loading some of your modules. To stir things up a little bit let's suppose that all your modules are stored directly at the root of the server and all the modules have an additional prefix (let's say the prefix consists of 'n/') which should be ignored when loading the module. On some nested page - eg [host]/path/to/page you want to define some entry point module with some dependency on some arbitrary module eg n/my/modulename . So you have:

define('entrypoint', ['n/my/modulename'], function(modulename){ .... });

But when you open the page, require.js decides to load your module according to the module name relatively to current document location - so it tries to fetch [host]/path/to/page/n/my/modulename . So far you think that the poor require.js is just blindly doing its work and does not know about your crazy location of your modules.

So how do you tell require to rewrite the path ? According to Require.js documentation we might try configuring it in a way similar to this:

require.config({
    baseUrl: '/'
})

That does not work

So let's try this

require.config({
    baseUrl: ''
})

No.

require.config({
    baseUrl: '/',
    paths: {
       n: ''
    }

})

Still wrong

require.config({
    baseUrl: '/',
    paths: {
       n: '/'
    }
})

Almost there. Now you realize that the require tries to load your modules from this path: http://my/modulename and you start wondering what were the authors of the library smoking.

After some struggling I think I figured out the only suitable solution for my use case. You have to configure the require with this:

require.config({
    baseUrl: '/',
    paths: {
       n: 'FOO/../'
    }
})

Now it finally grabs the n/my/modulename from url http://[host]/my/modulename .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM