简体   繁体   English

Require.js-加载相对于服务器根目录的模块

[英]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. 假设您有一个大型Web应用程序,并且决定使用require.js加载某些模块。 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. 为了使事情更容易些,让我们假设所有模块都直接存储在服务器的根目录下,并且所有模块都有一个附加前缀(假设前缀由“ n /”组成),在加载模块时应将其忽略。 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 . 在某些嵌套页面上,例如[host]/path/to/page您想要定义一些依赖于某些任意模块(例如n/my/modulename入口点模块。 So you have: 所以你有了:

define('entrypoint', ['n/my/modulename'], function(modulename){ .... }); 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 . 但是,当您打开页面时,require.js决定根据相对于当前文档位置的模块名称加载模块-因此它尝试获取[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. 到目前为止,您认为可怜的require.js只是盲目地工作,并且不知道模块的疯狂位置。

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.js文档,我们可以尝试以类似于以下方式进行配置:

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. 现在,您意识到require尝试从以下路径加载模块: http://my/modulename ,您开始怀疑该库的作者是谁。

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 . 现在,它终于抓住n/my/modulename从URL http://[host]/my/modulename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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