Grunt任务将文件内容注入另一个文件中的占位符 [英] Grunt task to inject a files contents into a placeholder within another file

查看:160
本文介绍了Grunt任务将文件内容注入另一个文件中的占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为toInject.js的JavaScript文件。我希望将此文件的内容注入到另一个JavaScript文件中,以代替注释占位符 / * === toInject.js占位符=== * / 到一个咕噜的任务。



咕噜任务前的两个文件都已运行:



toInject.js

  alert('hello world'); 

myScript.js

 函数doSomething(){
/ * === toInject.js占位符=== * /
}

运行grunt任务后对myScript.js所做的更改

myScript.js

 函数doSomething(){
alert('hello world');


解决方案

您可以动态设置任务配置:

  module.exports = function(grunt){
grunt.loadNpmTasks('grunt-replace');
grunt.initConfig({
替换:{
dist:{
options:{
patterns:[{
match:'foo',
replacement:'bar'
}]
},
files:[
{expand:true,flatten:true,src:['src / index.html'] ,dest:'build /'}
]
}
}
});

//注册自定义任务
grunt.registerTask('replaceByFileContents','Description',function(){
//获取文件
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)
});
//运行任务
grunt.task.run(replace:dist)
})
});


I have a JavaScript file called toInject.js. I would like the contents of this file to be injected into another JavaScript file in the place of a comment placeholder /* === toInject.js placeholder === */ through a grunt task. What grunt task is available to do this any what configuration is required?

Both files before grunt task has run:

toInject.js

alert('hello world');

myScript.js

function doSomething() {
    /* === toInject.js placeholder === */
}

Changes to myScript.js after grunt task has run:

myScript.js

function doSomething() {
    alert('hello world');
}

解决方案

You can dynamicly set task configs:

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)
  })
});

这篇关于Grunt任务将文件内容注入另一个文件中的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆