【发布时间】:2015-09-06 03:00:18
【问题描述】:
使用RequireJS,我不相信我完全理解“require”的以下两种不同用法之间的区别。在这种情况下,我只谈论浏览器,而不是 node.js。我的一个问题是:我可以在前端使用 RequireJS 同步需要某些依赖项吗?
首先是这样的:
define(function(){
//below the require is definitely the global require of RequireJS, also aliased as requirejs.
require(['module'],function(mod){
//mod is loaded here only
}
});
然后是这样的:
define(['require'],function(require){
require(['dep'],function(dep){ //require is local not global
//dep is loaded here only
}
//now the require subsequently called is the 'local' require
var dep = require('dependency'); //I doubt this is possible on front-end..or is it?
});
我想我看不到使用 require 作为参数在前端定义的目的,但是有吗?
我的困惑是因为这里的这个例子:
http://requirejs.org/docs/api.html
define() 中的相对模块名称: For require("./relative/name") 可能在 define() 函数调用中发生的调用,请务必询问 将“require”作为依赖项,以便解析相对名称 正确:
define(["require", "./relative/name"], function(require) {
var mod = require("./relative/name");
});
从上面我只能猜测,如果一个模块相对于另一个模块,你可以在前端使用 RequireJS 对其他模块进行同步调用?
同样,这个例子:
生成相对于模块的 URL:您可能需要生成一个 URL 是相对于模块的。为此,要求将“require”作为依赖项 然后使用 require.toUrl() 生成 URL:
define(["require"], function(require) {
var cssUrl = require.toUrl("./style.css");
});
所以,我的问题是:本地需求和全局需求有什么区别?看起来本地 require 显然不是仅/主要用于 CommonJS 模块。
【问题讨论】:
标签: javascript requirejs