webpack 4 - split chunks plugin for multiple entries

Daniel picture Daniel · May 8, 2018 · Viewed 9.3k times · Source

Using split chunks plugin with the following config :

{
    entry: {
        entry1: [entry1.js],
        entry2: [entry2.js],
        entry3: [entry3.js],
        ...
    }
    optimization: {
        splitChunks: {
            chunks: "all"
        }
    } 
}

The code would get perfectly split into:

vendors-entry1-entry2-entry3.js // common for all
vendors-entry1-entry3.js // vendors only required by both entry1, entry3
entry1-entry2.js // common code of entry1 and entry2
entry1.js // unique entry's code
entry2.js
entry3.js

Question is, how do i now use the specific vendors per entry in my html (or ejs in my specific case)?

Using HtmlWebpackPlugin as recommended would simply create an index.html which loads all of the above, although the use case is clearly:

When rendering entry1 page - load:

vendors-entry1-entry2-entry3.js
vendors-entry1-entry3.js
entry1-entry2.js
entry1.js

When rendering entry2 page - load:

vendors-entry1-entry2-entry3.js
entry1-entry2.js
entry2.js

etc..

Answer

ghost28147 picture ghost28147 · Jul 22, 2018

Version 4 of HtmlWebpackPlugin (which is alpha as of now) includes all entries' generated chunks automatically. So just setting chunks: 'entry1' should work:

new HtmlWebpackPlugin({
    template: 'entry1.ejs',
    filename: 'entry1.html',
    chunks: ['entry1']
}),

... and leads to injecting of all dependent chunks in html file:

<script src="/vendors-entry1-entry2-entry3.js">
<script src="/vendors-entry1-entry3.js">
<script src="/entry1-entry2.js">
<script src="/entry1.js">

You can install it with

npm install --save-dev html-webpack-plugin@next