Grunt Task Runner 连接文件

Grunt Task Runner to concatenate files

我正在编写 grunt 以动态连接文件,因为我的 grunt.config 变量中有文件数组。如何在 grunt concat 中使用它。

我正在通过动态文本替换功能编写 grunt.config('jsResources', targetConfig);。它作为数组返回。如何在 grunt concat 中使用它。我尝试过这种方式,但那不值得。

我的jsResources是数组。我的咕噜声就像

concat: {
    js: {
        //Concatenate all of the files in the jsResources configuration property
        src: ['app/<%= jsResources %>'],
        dest: 'build/views/js/combined.js',
        options: {
            separator: ';\n'
        }
    }            
}

它正在重装内容但无法读取内容,并连接到我的combine.js 我的 'jsResources' 就像 ['scripts/modules/allModules.js','scripts/config/constants.js','...'] 它正在创建空文件 combine.js.

所以我又试了一次,这是结果:

您需要先生成路径,然后再将它们放入模板变量中。模板变量这里是一个对象,但可以是任何有效的jsmore info。在其中,您可以设置以数组为值的属性。

module.exports = function(grunt) {

  var myFiles = {
    jsResources: ['file1.js', 'file2.js']
  };

  myFiles.jsResources = myFiles.jsResources.map(function(item) { return 'app/' + item; });

  // var jsres = myFiles.jsResources; // another way

  grunt.initConfig({
    // myFiles: myFiles, // this is also possible instead of grunt.config() below
    concat: {
      dist: {
        src: ['<%= myFiles.jsResources %>'], // src: ['<%= jsres %>'],
        dest: 'dest.js',
      },
      options: {
        separator: '\n'
      }
    }
  });

  grunt.config('myFiles', myFiles);
  // grunt.config('jsres', jsres); // another way

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.registerTask('default', ['concat:dist']);

};

这会生成 dest.js 内容。

Edin 的回答是解决此问题的好方法。另一种解决方案是(ab)使用 expand/cwd 选项,如下所示:

grunt.initConfig({
  jsDir: 'app',
  jsResources: [ 'one.js', 'two.js' ],

  concat: {
    app: {
      expand: true,
      cwd: '<%= jsDir %>',
      src: ['<%= jsResources %>'],
      dest: 'dest.js',
      rename: function (dest) { return dest; }
    }
  }
});

请注意,expand: true 通常用于动态 src/dest 映射,通常有许多 src/dest 对(而不是映射到单个目标的源数组,如grunt-contrib-concat)。但是,在这种情况下,它可以与 rename 选项(简要记录 here)结合使用来实现您想要的。

这是一种 hacky 方法,但它具有声明性的优点(以 Grunt 的风格)并且允许配置工作目录(如我在上面 jsDir 所示)。