Exclude specific packages from bundle in Webpack

佐手、 提交于 2021-02-10 06:47:16

问题


I am trying to find a way to exclude specific package of a subdepedency from my Webpack bundle. I tried many ways, my recent attempt is to (ab)use the externals options like:

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();
    },
],

Without success, is any other way to achieve that?

I have a vendors bundle that looks like:

I want to exlcude the dublicate packages under the node-modules, e.g. react-dom.

Entry

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

回答1:


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




回答2:


You should be able to exclude a specific package in the loader config:

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

Updated:

Ah okay makes sense, in that case, I would make a separate chunk for just that package. Then using HTMLWebpackPlugin, you can tell it to ignore that chunk and not pull it into the app:

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

Update 2:

Sounds like what you want is to dedupe dependencies. You can't do this using Webpack, you'll need to use npm or yarn:

For example, consider this dependency graph:

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

In this case, npm-dedupe will transform the tree to:

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


来源:https://stackoverflow.com/questions/48586605/exclude-specific-packages-from-bundle-in-webpack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!