如何在不重复webpack

时间:2017-06-15 21:27:54

标签: webpack concatenation frontend

由于我在我的应用程序中连接了许多文件,因此我不想一次又一次地编写相同的插件。我的方法是连接与我的应用程序中的特定模块相关的单个文件。请告知。

const ConcatPlugin = require('webpack-concat-plugin');

new ConcatPlugin({
    useHash: true, // md5 file
    sourceMap: true, // generate sourceMap
    options: {
        process: function(src, filepath) {
            src = src.replace('"use strict";','');
            return '$(function () {\n' + src + '\n});';
        }
    },
    fileName: 'js/react/_react.es6.do-not-edit.js',
    filesToConcat: [
        './js/react/promises.js',
        './js/react/comps.js',
        './js/react/press-release-component.js'
    ]
}),
new ConcatPlugin({
    useHash: true, // md5 file
    sourceMap: true, // generate sourceMap
    options: {
        process: function(src, filepath) {
            src = src.replace('"use strict";','');
            return '$(function () {\n' + src + '\n});';
        }
    },
    fileName: globalPath.theme + '/js/script.min.js',
    filesToConcat: [
        './js/languages.min.js',
        './js/_script.min.do-not-edit.js',
        './js/_react.es5.min.do-not-edit.js'
    ]
}),
new ConcatPlugin({
    useHash: true, // md5 file
    sourceMap: true, // generate sourceMap
    options: {
        process: function(src, filepath) {
            src = src.replace('"use strict";','');
            return '$(function () {\n' + src + '\n});';
        }
    },
    fileName: globalPath.theme + '/js/script.js',
    filesToConcat: [
        './js/script.js',
        './js/_react.es5.do-not-edit.js'
    ]
}),

1 个答案:

答案 0 :(得分:0)

创建一个可以获取文件组数组的函数,这些文件组只是要连接的文件。通过这些来迭代创建插件实例并返回插件实例数组。您可能还需要使用扩展运算符。

let appFileGroups = [
        [
          './js/script.js',
          './js/_react.es5.do-not-edit.js'
        ],
        [
          './js/script.js',
          './js/_react.es5.do-not-edit.js'
        ],
    ];



function concatFileGroups(fileGroups) {
   return fileGroups.map(fileGroup => {
     new ConcatPlugin({
         useHash: true, // md5 file
         sourceMap: true, // generate sourceMap
         options: {
             process: function(src, filepath) {
                 src = src.replace('"use strict";','');
                 return '$(function () {\n' + src + '\n});';
             }
         },
         fileName: globalPath.theme + '/js/script.js',
         filesToConcat: fileGroup 
      })
   }
}

在webpack配置中:

  plugins : [
     concatFileGroups(appFileGroups),
     // if that doesnt work try this
     //...concatFileGroups(appFileGroups),
     // remaining plugins