kazaxy
kazaxy

Reputation: 41

Create vendor.bundle for each entry with webapack 4

I want to make vendor.bundle for each entry with webapack4.
example.

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

After building.

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

How do I configure split chunks?
Current config.

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

I tried to handle name with a function instead of a string, but it did not work.

Thank you.

Upvotes: 1

Views: 445

Answers (1)

kazaxy
kazaxy

Reputation: 41

Solved this problem.

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`
        },
      }
    }
  },
}

Upvotes: 3

Related Questions