Webpack using node_modules in vendor chunk without explicitly stating them

前端 未结 1 511
青春惊慌失措
青春惊慌失措 2021-01-23 22:06

So code splitting is the technique of creating different bundles - so app, vendor etc...

I know what I want in my vendor bundle but only by convention...

相关标签:
1条回答
  • 2021-01-23 22:32

    What you can do is this:

    const pkg = require('./package.json');

    and in your configuration:

    {
       entry: {
          vendor: Object.keys(pkg.dependencies) // use node_module dependencies
       },
       plugins: [
         new webpack.optimize.CommonsChunkPlugin({
            name: "vendor"
         })
       ]
    }
    

    EDIT: It seems there is a better way to do it. One can use minChunks property in the CommonsChunkPlugin plugin. You can pass a function there, as such:

    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: "vendor",
            minChunks: ({ resource }) => {
                return resource && resource.match(/\.js$/) && resource.indexOf('node_modules') >= 0;
            }
        })
    ]
    

    By doing that, you don't need to rely on package.json list and webpack will consider only dependencies used in the project. neat.

    0 讨论(0)
提交回复
热议问题