2012-10-04 36 views
13

要連接兩個文件,它看起來是這樣的:使用grunt concat,我將如何自動將同一個文件連接到許多其他文件?

concat: { 
    src: ['common.js','js/app.js'], 
    dest: 'assets/js/app.js' 
    } 

如果我想Concat的整個文件夾爲一體,它看起來是這樣的:

concat: { 
    src: ['dev/*.js','], 
    dest: 'prod/js/app.js' 
    } 

但是,假設我有一個文件,我想連接到10或20個其他文件,我希望他們分別連接?換句話說,這裏就是我在尋找:

A.js + B.js = AB.js 
A.js + C.js = AC.js 
A.js + D.js = AD.js 
A.js + E.js = AE.js 

等等......更具體的,雖然,我可以弄清楚如何描述Concat的文件一個接一個,但我想找出如何從示例中指定A.js,並將其連接到指定路徑中的任何文件。所以,我要的是:

A.js + dev/*.js = AB.js, AC.js, AD.js, AE.js ... 

在僞代碼,這裏就是我想:

concat: { 
    src: ['common.js', 'dev/*.js','], // common.js gets concatenated to each file in this directory 
    dest: 'prod/js/*.js' // each file in src gets saved separately in dest 
    } 

我想感謝所有幫助,我已經有一個困難時期如何尋找信息做這個

+0

如果有人需要一個類似的東西,這個插件只需要https://www.npmjs.org/package/grunt-wrap2000 – Tetaxa

+0

所有你需要做的就是使用grunt-contrib-concat中的橫幅和頁腳選項。如果你想要一個完整的文件,只需要執行'banner:require('./ foo.js')'。與頁腳相同。 – jonschlinkert

回答

19

Grunt的內置concat任務(我建議看看源btw)不支持任何像dest: 'prod/js/*.js'任何東西,你將不得不分別指定每個輸出目標,這是在你的情況是一個矯枉過正。

最好的辦法是編寫自己的代碼(也許將其包裝在自定義任務中),這很簡單。這裏有一個簡單的包裝多任務。不保證它的強大和安全的使用:)

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.'); 
     }); 
    }); 

有了這樣的配置給它:

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

以防萬一,我還更新了你的提琴:http://jsfiddle.net/dipish/hKkGX/

+0

爲了澄清,我想爲每個文件分別進行連接,那麼您還可以使用dest:'prod/js/*。js'嗎?並感謝您的回答! – jonschlinkert

+0

更新的答案是否適合您? –

+0

它看起來應該是這樣,但我無法讓它工作。我知道這是很多要問的,你有可能把它放在一個示例grunt文件中?這裏是一個jsfiddle與我的grunt文件 - 只是爲了更容易閱讀http://jsfiddle.net/rRpeg/ – jonschlinkert

相關問題