使用 RequireJS 命名模块
Naming modules with RequireJS
我想知道如何在不使用模块本身的相对路径的情况下命名模块。
例如:
而不是这样做:
//module is defined in app/js/routers.js
define('app/js/routers',['app/js/currentView'],function(currentView) {
});
我宁愿这样做:
//module is defined in app/js/routers.js
define('routers',['app/js/currentView'],function(currentView) {
});
这是可能的还是一个坏主意?显然,您为每个模块指定的名称必须是唯一的。我想我只是不知道定义调用中可选的第一个参数是否必须与其包含的脚本路径相同。
I guess I just don't the see point of the optional first parameter in the define call if it has to be same as the path of script it's contained in.
是的,如果您要将模块放在一个文件中,该文件的路径相对于您在 RequireJS 配置中提供的 baseURL
是模块的名称,那么您可以 not 必须向 define
提供模块名称。事实上,在这种情况下,您 不应该 给出模块名称。 RequireJS documentation 状态:
These [i.e. module names] are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.
(强调已添加。)
我想知道如何在不使用模块本身的相对路径的情况下命名模块。
例如:
而不是这样做:
//module is defined in app/js/routers.js
define('app/js/routers',['app/js/currentView'],function(currentView) {
});
我宁愿这样做:
//module is defined in app/js/routers.js
define('routers',['app/js/currentView'],function(currentView) {
});
这是可能的还是一个坏主意?显然,您为每个模块指定的名称必须是唯一的。我想我只是不知道定义调用中可选的第一个参数是否必须与其包含的脚本路径相同。
I guess I just don't the see point of the optional first parameter in the define call if it has to be same as the path of script it's contained in.
是的,如果您要将模块放在一个文件中,该文件的路径相对于您在 RequireJS 配置中提供的 baseURL
是模块的名称,那么您可以 not 必须向 define
提供模块名称。事实上,在这种情况下,您 不应该 给出模块名称。 RequireJS documentation 状态:
These [i.e. module names] are normally generated by the optimization tool. You can explicitly name modules yourself, but it makes the modules less portable -- if you move the file to another directory you will need to change the name. It is normally best to avoid coding in a name for the module and just let the optimization tool burn in the module names. The optimization tool needs to add the names so that more than one module can be bundled in a file, to allow for faster loading in the browser.
(强调已添加。)