How to bundle vendor scripts separately and require them as needed with Webpack?

后端 未结 4 1746
我寻月下人不归
我寻月下人不归 2020-11-28 17:51

I\'m trying to do something that I believe should be possible, but I really can\'t understand how to do it just from the webpack documentation.

I am writing a JavaSc

4条回答
  •  Happy的楠姐
    2020-11-28 18:03

    in my webpack.config.js (Version 1,2,3) file, I have

    function isExternal(module) {
      var context = module.context;
    
      if (typeof context !== 'string') {
        return false;
      }
    
      return context.indexOf('node_modules') !== -1;
    }
    

    in my plugins array

    plugins: [
      new CommonsChunkPlugin({
        name: 'vendors',
        minChunks: function(module) {
          return isExternal(module);
        }
      }),
      // Other plugins
    ]
    

    Now I have a file that only adds 3rd party libs to one file as required.

    If you want get more granular where you separate your vendors and entry point files:

    plugins: [
      new CommonsChunkPlugin({
        name: 'common',
        minChunks: function(module, count) {
          return !isExternal(module) && count >= 2; // adjustable
        }
      }),
      new CommonsChunkPlugin({
        name: 'vendors',
        chunks: ['common'],
        // or if you have an key value object for your entries
        // chunks: Object.keys(entry).concat('common')
        minChunks: function(module) {
          return isExternal(module);
        }
      })
    ]
    

    Note that the order of the plugins matters a lot.

    Also, this is going to change in version 4. When that's official, I update this answer.

    Update: indexOf search change for windows users

提交回复
热议问题