今天下午我一直在试验 Grunt 和 Require JS。我是 text
模块的忠实粉丝,我用它来引入我的模板。在非基于 Grunt 的项目中,我使用了 inlineText
和 stubModules
Require JS 选项来内联模板文件,效果很好。但是,我无法让它与 Grunt 一起使用。
需要配置
require.config({
paths: {
// Using Bower for dependency management
text: '../components/requirejs-text/text'
}
});
用法
define(['text!template.html'], function (html) {
// Do stuff with html
});
Gruntfile.js
requirejs: {
dist: {
options: {
baseUrl: 'app/scripts',
optimize: 'none',
preserveLicenseComments: false,
useStrict: true,
wrap: true,
inlineText: true,
stubModules: ['text']
}
}
}
运行 grunt
后,控制台出现各种错误:
/dist/components/requirejs-text/text.js 上找不到文件
模块加载超时:text!template.html_unnormalized2
那么两个问题:
text.js
代码template.html
文件任何想法为什么它不起作用?
最佳答案
您看到错误是因为您需要向 r.js
指出 text
模块在哪里。
您可以通过添加路径配置来做到这一点:
requirejs: {
dist: {
options: {
baseUrl: 'app/scripts',
optimize: 'none',
preserveLicenseComments: false,
useStrict: true,
wrap: true,
inlineText: true,
stubModules: ['text'],
paths: {
'text': 'libs/text' // relative to baseUrl
}
}
}
}
然后您需要将 text.js
模块下载到相应的目录中。
但是为什么您的 require.config
不起作用?
因为 r.js
需要在某个时候评估配置。您没有在问题中提到 require.config
在哪里,但如果您想评估它,您需要指出 r.js
的位置(请参阅https://github.com/jrburke/r.js/blob/master/build/example.build.js#L35):
requirejs: {
dist: {
options: {
baseUrl: 'app/scripts',
optimize: 'none',
preserveLicenseComments: false,
useStrict: true,
wrap: true,
inlineText: true,
stubModules: ['text'],
mainConfigFile: '../config.js' // here is your require.config
// Optionally you can use paths to override the configuration
paths: {
'text': 'libs/text' // relative to baseUrl
}
}
}
}
https://stackoverflow.com/questions/15866683/