我有一个名为 toInject.js 的 JavaScript 文件。我希望通过 grunt 任务将该文件的内容注入(inject)到另一个 JavaScript 文件中,以代替注释占位符 /* === toInject.js placeholder === */
。需要什么配置才能执行此操作?
grunt 任务运行之前的两个文件:
toInject.js
alert('hello world');
myScript.js
function doSomething() {
/* === toInject.js placeholder === */
}
grunt 任务运行后对 myScript.js 的更改:
myScript.js
function doSomething() {
alert('hello world');
}
最佳答案
您可以动态设置任务配置:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-replace');
grunt.initConfig({
replace: {
dist: {
options: {
patterns: [{
match: 'foo',
replacement: 'bar'
}]
},
files: [
{expand: true, flatten: true, src: ['src/index.html'], dest: 'build/'}
]
}
}
});
// register custom task
grunt.registerTask('replaceByFileContents', 'Description', function() {
// get files
grunt.file.expand({cwd: 'src', '**/*.js'}).map(function(file) {
// set config: replace 'index.js' by index.js content
grunt.config.set('replace.dist.option.patterns', {
match: file,
replacement: grunt.file.read(file)
});
// run task
grunt.task.run(replace:dist)
})
});
关于javascript - 将文件内容注入(inject)另一个文件中的占位符的 Grunt 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25014200/