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

后端 未结 1 1728
情深已故
情深已故 2020-12-14 04:12

To concatenate two files, it looks something like this:

  concat: {
    src: [\'common.js\',\'js/app.js\'],
    dest: \'assets/js/app.js\'
  }
相关标签:
1条回答
  • 2020-12-14 04:13

    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/

    0 讨论(0)
提交回复
热议问题