使用webapack 4为每个条目创建vendor.bundle

时间:2018-12-14 11:00:41

标签: javascript webpack webpack-splitchunks

我想使用webapack4为每个条目创建vendor.bundle。
例子。

src/
  pages/
    home/
     index.js
    list/
     index.js

建立之后。

dist/
  pages/
    home/
      index.bundle.js
      home.vendor.bundle.js
    list/
      index.bundle.js
      list.vendor.bundle.js

如何配置拆分块?
当前配置。

const path = require('path')

module.exports = {
  mode: 'development',

  entry: {
    '/pages/home/index': path.resolve(__direname, 'src', 'pages', 'home', 'index.js'),
    '/pages/list/index': path.resolve(__direname, 'src', 'pages', 'list', 'index.js'),
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
  },

  // I am troubled with the setting here.
  optimization: {
    runtimeChunk: {
      name: 'runtime'
    },
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          chunks: 'all',
          enforce: true,
          name: 'vendor'
        },
      }
    }
  },
}

我尝试使用函数而不是字符串来处理名称,但这没有用。

谢谢。

1 个答案:

答案 0 :(得分:1)

解决了这个问题。

const path = require('path')
module.exports = {
  mode: 'development',

  entry: {
    '/pages/home/index': path.resolve(__direname, 'src', 'pages', 'home', 'index.js'),
    '/pages/list/index': path.resolve(__direname, 'src', 'pages', 'list', 'index.js'),
  },

  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].bundle.js',
  },

  optimization: {
    runtimeChunk: {
      name: 'runtime'
    },
    splitChunks: {
      cacheGroups: {
        'top-vendor': {
          test: /[\\/]node_modules[\\/]/,
          chunks: chunk => chunk.name === '/pages/home/index',
          enforce: true,
          name: `${path.dirname('/pages/home/index')}/vendor`
        },
        'list-vendor': {
          test: /[\\/]node_modules[\\/]/,
          chunks: chunk => chunk.name === '/pages/list/index',
          enforce: true,
          name: `${path.dirname('/pages/list/index')}/vendor`
        },
      }
    }
  },
}