Using grunt concat, how would I automate the concatenation of the same file to many other files?

不想你离开。 提交于 2019-11-28 19:41:06

Grunt's built-in concat task (I recommend looking at the source btw) does not support anything like dest: 'prod/js/*.js', you would have to specify each output target separately which is an overkill in your case.

Your best bet is to just write your own code (perhaps wrap it in your custom task), it's quite simple. Here's a simple wrap multitask. Don't promise it's robust and safe to use :)

  grunt.registerMultiTask('wrap', 'Wraps source files with specified header and footer', function() {
        var data = this.data,
            path = require('path'),
            dest = grunt.template.process(data.dest),
            files = grunt.file.expandFiles(this.file.src),
            header = grunt.file.read(grunt.template.process(data.header)),
            footer = grunt.file.read(grunt.template.process(data.footer)),
            sep = grunt.utils.linefeed; 

        files.forEach(function(f) {
            var p = dest + '/' + path.basename(f),
                contents = grunt.file.read(f);

            grunt.file.write(p, header + sep + contents + sep + footer);
            grunt.log.writeln('File "' + p + '" created.');
        });
  });

Feed it with a config like this:

wrap: {
    html: {
        header: '<%= project.partials %>/head.html',
        footer: '<%= project.partials %>/footer.html',
        src: [
            '<%= project.pages %>/index.html',
            '<%= project.pages %>/about.html',
            '<%= project.pages %>/blog.html'
        ],
        dest: '.'   // destination *directory*, probably better than specifying same file names twice
    }
}

Just in case I also updated your fiddle: http://jsfiddle.net/dipish/hKkGX/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!