从Webpack中的bundle中排除特定包

时间:2018-02-02 16:08:41

标签: reactjs webpack

我试图找到一种方法从我的Webpack包中排除subdepedency的特定包。我尝试了很多方法,我最近的尝试是(ab)使用外部选项,如:

externals: [
    function externals(context, request, callback) {
        if (
        context.includes('ui-lib/node_modules/react-dom/') ||
        context.includes('ui-lib/node_modules/d3/') ||
        context.includes('ui-lib/node_modules/lodash/')
        ) {
        return false;
        }
        callback();
    },
],

没有成功,还有其他方法可以实现吗?

我有一个看似如下的供应商包:

enter image description here

我想要了解节点模块下的dublicate包,例如:反应-DOM。

条目

entry: {
  app: ['babel-polyfill', path.join(__dirname, './../index.dev.js')],
  vendor: ['react', 'react-dom', 'd3'],
},

CommonChunk

new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
  filename: 'vendorbundle.js',
  chunks: ['app'],
  minChunks(module) {
    return module.context && module.context.includes('node_modules');
  },
}),

2 个答案:

答案 0 :(得分:1)

For future reference, external libraries that use React need to declare it as peerDepedency. Doing that removed one of the react-dom instances:

enter image description here

答案 1 :(得分:0)

您应该能够在加载程序配置中排除特定的包:

  {
    test: /\.js$/,
    exclude: [/node_modules\/SUBDEPENDENCY_PATH/]
  },

<强>更新

啊,没关系,在这种情况下,我会为那个包制作一个单独的块。然后使用HTMLWebpackPlugin,您可以告诉它忽略该块而​​不是将其拉入应用程序:

entry: {
  sub: ["subdependency"],
  app: "./entry"
},
plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: "sub",
    filename: "sub.js"
  }),
  new HtmlWebpackPlugin({
    excludeChunks: ['sub']
  })
]

更新2:

听起来像你想要dedupe dependencies。您无法使用Webpack执行此操作,您需要使用npm或yarn:

例如,请考虑此依赖关系图:

a
+-- b <-- depends on c@1.0.x
|   `-- c@1.0.3
`-- d <-- depends on c@~1.0.9
    `-- c@1.0.10

在这种情况下,npm-dedupe会将树转换为:

a
+-- b
+-- d
`-- c@1.0.10