[英]How to use relative paths in require.config?
我想分發一段代碼作為AMD模塊。 該模塊在noConflict模式下依賴jQuery,並帶有兩個jQuery插件。
我希望用戶能夠只需要一個模塊文件即可使用該模塊(模塊將托管在我們的服務器上),並為它們處理依賴項。 但是,為了正確加載依賴項,我必須調用require.config()
,它似乎具有相對於網頁的模塊路徑,而不是相對於調用腳本的路徑。 我可以使用paths
配置使所有路徑都是絕對的。 這將解決依賴性問題,但也會使生產服務器外部的任何測試成為噩夢。
更具體地說,模塊文件大致如下所示:
define (['./jquery-wrapper'], function ($) {
...
return module;
});
同一目錄中的jquery-wrapper.js
文件如下所示:
require.config ({
paths: {
'jquery-original': '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min',
// ^ naturally, this one has to be absolute
},
shim: {
'jquery-original': {
exports: '$',
},
'../plugin/js/jquery.nouislider.min': {
// ^ this path is relative to the web page, not to the module
deps: ['jquery-original'],
},
'../plugin/js/jquery.ie.cors': {
// ^ this path is relative to the web page, not to the module
deps: ['jquery-original'],
},
},
});
define (['jquery-original', './jquery.nouislider.min', './jquery.ie.cors'], function ($, slider, cors) {
// ^ these paths are relative to the module
console.log ('types: ' + typeof slider + typeof $.noUiSlider + typeof cors);
return $.noConflict (true);
});
有什么方法可以在任何地方使用相對於模塊的路徑嗎?
我認為您可以使用單獨的配置來使其正常工作:
在此示例中, other/module
路徑模擬了其他服務器。
¦ a.js
¦ b.js
¦ c.js
¦ test.html
¦
+---other
+---module
main.js
module-file-1.js
具有相關性,使用相對的模塊名稱。
define(["./module-file-1"], function (mf1) {
console.log("load main", "deps", mf1);
return "main";
});
具有相關性,使用相對的模塊名稱。
define(["./b"], function(b) {
console.log("load a", "deps", b);
return "a";
});
沒意思
define(function () {
console.log("load b");
return "b";
});
沒意思
define(function () {
console.log("load module-file-1");
return "module-file-1";
});
設置兩個require上下文,使用每個上下文來加載自己的模塊,然后等待兩組模塊加載:
<script src="http://requirejs.org/docs/release/2.1.8/comments/require.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var localRequire = require({
context: "local"
});
var moduleRequire = require({
context: "module",
baseUrl: "http://localhost/other/module/"
});
function deferredRequire(require, deps) {
return $.Deferred(function(dfd) {
require(deps, function() {
dfd.resolve.apply(dfd, arguments);
});
}).promise();
}
$.when(deferredRequire(moduleRequire, ["main"]), deferredRequire(localRequire, ["a", "b", "c"])).then(function(deps1, deps2) {
// deps1 isn't an array as there's only one dependency
var main = deps1;
var a = deps2[0];
var b = deps2[1];
var c = deps2[2];
console.log("Finished", main, a, b, c);
});
</script>
load b
load a deps b
load c
load module-file-1
load main deps module-file-1
Finished main a b c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.