繁体   English   中英

Grunt Task Runner连接文件

[英]Grunt Task Runner to concatenate files

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

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

我的jsResources是数组。 我的咕unt就像

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 more 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

爱丁的答案是解决这个问题的好方法。 另一个解决方案是(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所示)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM