拆分"供应商"使用webpack 2的块

时间:2017-06-27 15:42:41

标签: javascript webpack webpack-2 code-splitting commonschunkplugin

我的代码拆分配置类似于官方docs 一切都很完美 - 我所有的节点模块都在"供应商"大块(包括" babel-polyfill")。但现在我需要将babel-polyfill及其所有依赖项移到单独的块(" polyfills"),以便能够在我的供应商捆绑之前加载它。任何想法如何做到这一点?

我的配置:

...
entry: {
  main: './index.jsx'
},
...
new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
  minChunks: function (module) {
    return module.context && module.context.indexOf('node_modules') !== -1;
  }
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'manifest' })
...

1 个答案:

答案 0 :(得分:1)

获取依赖项

您可以阅读package.json

中的babel-polyfill
const path = require('path');

function getDependencies () {

       // Read dependencies...
       const { dependencies } = require('node_modules/babel-polyfill/package.json');

       // Extract module name
       return Object.keys(dependencies);
}

只需调用它(应返回包含dependencies的数组):

const dependencies = getDependencies(); // ['module', ...]

检测polyfills

检查模块是babel-polyfill还是依赖:

 function isPolyfill(module){

     // Get module name from path
     const name = path.posix.basename(module.context)              

     // If module has a path 
     return name &&

     // If is main module or dependency
     ( name === "babel-polyfill" || dependencies.indexOf(name) !== -1 ); 
 }

要删除babel-polyfill和依赖项,只需检查是否返回false

new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: function (module) {

        // If has path
        return module.context &&

        //If is a node-module
        module.context.indexOf('node_modules')!== -1 &&

        // Remove babel-polyfill and dependencies
        isPolyfill(module) === false;
    }
})

创建polyfills chunk

要仅选择babel-polyfill和依赖项,只需检查是否返回true

new webpack.optimize.CommonsChunkPlugin({
    name: 'polyfills',

    minChunks: function (module) {

        // If has a path
        return module.context &&

        //If is a node-module
        module.context.indexOf('node_modules')!== -1 &&

        // Select only  babel-polyfill and dependencies
        isPolyfill(module) === true;
    }
})