D
D
dannyfromtheblock2019-10-24 12:44:07
webpack
dannyfromtheblock, 2019-10-24 12:44:07

How to include different vendor scripts for different pages in Webpack?

I have a multi-page project that is built by Webpack.
I specified several entry points in the config:

entry: {
 'main': './src/main.js',
 'page.a': './src/page.a.js',
 'page.b': './src/page.b.js'
}

They, in turn, import various scripts from /node_modules/ .
Using splitChunks, I collect vendor scripts into separate files:
splitChunks: {
 cacheGroups: {
  vendor: {
   test: /[\\/]node_modules[\\/].*\.js$/,
   chunks: 'all'
  }
 }
}

The output is the following files:
  • main.js
  • page.a.js
  • page.b.js
  • vendor~main.js
  • vendor~page.a.js
  • vendor~page.b.js

The pages themselves are created as follows:
new HtmlWebpackPlugin({
 template: `${paths.src}/template/pages/main.pug`,
 filename: 'main.html'
}),
new HtmlWebpackPlugin({
 template: `${paths.src}/template/pages/page.a.pug`,
 filename: 'page.a.html'
}),
new HtmlWebpackPlugin({
 template: `${paths.src}/template/pages/page.b.pug`,
 filename: 'page.b.html'
})

Question: how to make the files with vendor scripts vendor~page.a.js and vendor~page.b.js connected according to their pages? And vendor~main.js was connected on all pages.
As a result, you need to connect scripts according to the following scheme:
main.html
  • vendor~main.js
  • main.js

page.a.html
  • vendor~main.js
  • vendor~page.a.js
  • page.a.js
  • main.js

page.b.html
  • vendor~main.js
  • vendor~page.b.js
  • page.b.js
  • main.js

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
whiteua, 2020-06-03
@whiteua

I think this solution will work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question