mil*_*man 8 javascript requirejs underscore.js
有没有办法在使用RequireJS时设置templateSettingsfor lodash?
现在我在我的主要创业公司,
require(['lodash', 'question/view'], function(_, QuestionView) {
var questionView;
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
evaluate: /\{\%(.+?)\%\}/g
};
questionView = new QuestionView();
return questionView.render();
});
Run Code Online (Sandbox Code Playgroud)
但它似乎并不想设置templateSettings全局,因为当我_.template(...)在模块中使用时,它想要使用默认值templateSettings.问题是我不想在每个使用的模块中更改此设置_.template(...).
Leo*_*rdo 16
基于@Tyson Phalp建议,这意味着这个问题.
我根据您的问题对其进行了调整,并使用RequireJS 2.1.2和SHIM配置对其进行了测试.
这是main.jsrequireJS配置所在的文件:
require.config({
/* The shim config allows us to configure dependencies for
scripts that do not call define() to register a module */
shim: {
underscoreBase: {
exports: '_'
},
underscore: {
deps: ['underscoreBase'],
exports: '_'
}
},
paths: {
underscoreBase: '../lib/underscore-min',
underscore: '../lib/underscoreTplSettings',
}
});
require(['app'],function(app){
app.start();
});
Run Code Online (Sandbox Code Playgroud)
然后你应该underscoreTplSettings.js用你的templateSettings 创建文件,如下所示:
define(['underscoreBase'], function(_) {
_.templateSettings = {
evaluate: /\{\{(.+?)\}\}/g,
interpolate: /\{\{=(.+?)\}\}/g,
escape: /\{\{-(.+?)\}\}/g
};
return _;
});
Run Code Online (Sandbox Code Playgroud)
因此,您的模块underscore将包含下划线库和模板设置.
从您的应用程序模块中只需要underscore模块,这样:
define(['underscore','otherModule1', 'otherModule2'],
function( _, module1, module2,) {
//Your code in here
}
);
Run Code Online (Sandbox Code Playgroud)
我唯一的疑问是我输出了_两次相同的符号,即使这项工作很艰难,我也不确定这是不是一个好习惯.
=========================
替代解决方案: 这也很好用,我想它会更加干净,避免创建并需要额外的模块作为上述解决方案.我使用初始化函数更改了Shim配置中的'export'.有关进一步了解,请参阅Shim配置参考.
//shim config in main.js file
shim: {
underscore: {
exports: '_',
init: function () {
this._.templateSettings = {
evaluate:/\{\{(.+?)\}\}/g,
interpolate:/\{\{=(.+?)\}\}/g,
escape:/\{\{-(.+?)\}\}/g
};
return _; //this is what will be actually exported!
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6481 次 |
| 最近记录: |