Grunt Task Runner连接文件

Grunt Task Runner to concatenate files

本文关键字:文件 连接 Runner Task Grunt      更新时间:2023-09-26

我正在编写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

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

在将路径放入模板化变量之前,需要先生成路径。模板变量这里是对象,但可以是任何有效的js详细信息。在它内部,您可以设置将数组作为值的属性。

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选项(此处简要介绍)一起使用,以实现您想要的功能。

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