ChunksWebpackPlugin

The ChunksWebpackPlugin creates HTML files with entry points and chunks relations to serve your webpack bundles. It is suitable with multiple page application which contains multiple entry points.

Since Webpack 4, SplitChunksPlugin offer the possibility to optimizes all chunks. It can be particularly powerful, because it means that chunks can be shared even between async and non-async chunks. See the webpack documentation for splitChunks.chunks.

This option automatically generate new chunks associated with an entry point. For example, entry points a.js and b.js share common codes with the file vendors~a~b.js.

With multiple entry points, it can be difficult to identify relation between auto-generated chunks and entry points.

The plugin parse the entrypoints Map object from the webpack compilation to get all valid entry points and associated files. Then, it generates HTML files which include all assets filtered by entry point and the chunks-manifest.json file.

Zero config

The plugin works without configuration. For advanced usage, see the section using configuration.

Installation

The plugin is available as a package with the name of chunks-webpack-plugin on npm and Github.

npm install chunks-webpack-plugin --save-dev
yarn add chunks-webpack-plugin --dev

Environment

ChunksWebpackPlugin was built for Node.js >=8.11.2 and webpack >=4.x.

Example

For example implementation, please see the Github documentation.

Basic usage

The plugin will generate two HTML files for each entry points. Each filename contains the entry point name, the {{entry}} placeholder is automatically replaced.

  • {{entry}}-styles.html: contains all HTML <link> tags
  • {{entry}}-scripts.html: contains all HTML <script> tags

First, let's add the plugin to the webpack configuration.

var ChunksWebpackPlugin = require('chunks-webpack-plugin');
var path = require('path');

module.exports = {
  entry: 'main.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, './dist')
  },
  plugins: [new ChunksWebpackPlugin()]
};

HTML files are built in the output path directory with all the other assets.

Then, include the HTML files in the wanted pages.

main-styles.html

<link rel="stylesheet" href="main.css" />

main-scripts.html

<script src="main.js"></script>

Using a configuration

You can pass configuration options to ChunksWebpackPlugin to overrides default settings. Allowed values are as follows:

outputPath

string = null

Tells the plugin whether to personalize the output path of the generated files.

new ChunksWebpackPlugin({
  outputPath: path.resolve(__dirname, './templates')
});

The default behavior will use the options.output.path from the webpack configuration.

The outputPath must be an absolute path.

fileExtension

string = '.html'

Tells the plugin whether to personalize the extension of the generated files.

new ChunksWebpackPlugin({
  fileExtension: '.html'
});

templateStyle

string = '<link rel="stylesheet" href="{{chunk}}" />'

Tells the plugin whether to personalize the default template for the HTML <style> tags. For example, add additional attributes, a CDN prefix or something else.

new ChunksWebpackPlugin({
  templateStyle: '<link rel="stylesheet" href="{{chunk}}" />'
});

Keep the {{chunk}} placeholder, it is automatically replaced by the concatenation of the webpack public path and the chunk filename.

templateScript

string = '<script src="{{chunk}}"></script>'

Tells the plugin whether to personalize the default template for the HTML <script> tags. For example, add additional attributes, a CDN prefix or something else.

new ChunksWebpackPlugin({
  templateScript: '<script src="{{chunk}}"></script>'
});

Keep the {{chunk}} placeholder, it is automatically replaced by the concatenation of the webpack public path and the chunk filename.

customFormatTags

false || function (chunksSorted, files)

Tells the plugin whether to personalize the default behavior for generate your own templates. The function is called for each entry points. Custom behavior can also be add for a specific entry point if necessary.

new ChunksWebpackPlugin({
  customFormatTags: (chunksSorted, Entrypoint) => {
    // Generate all HTML style tags with a CDN prefix
    const styles = chunksSorted.styles.map(chunkCss =>
      `<link rel="stylesheet" href="https://cdn.domain.com/${chunkCss}" />`
    ).join('');

    // Generate all HTML style tags with CDN prefix and defer attribute
    const scripts = chunksSorted.scripts.map(chunkJs =>
      `<script defer src="https://cdn.domain.com/${chunkJs}"></script>`
    ).join('');

    return { styles, scripts };
  }
});

The arrow function syntax allow you to access the class properties.

The function provides more flexibility by replacing the default behavior. Follow the example above to make sure it works.

The function must return an object with the following format:

{
  "styles": "",
  "scripts": ""
}

The customFormatTags function has two parameters:

chunksSorted

object

The list of the chunks sorted by type: styles and scripts.

Entrypoint

Object

The object is included in every single ChunkGroup. The variable contains all information about the current entry point; log it on the console for more details.

Use this variable only for a full customization if the chunksSorted variable does not meet your needs.

generateChunksManifest

boolean = false

Tells the plugin whether to generate the chunks-manifest.json. The file contains the list of all the chunks grouped by entry points.

new ChunksWebpackPlugin({
  generateChunksManifest: false
});

Example of the output of the chunks-manifest.json file:

{
  "app-a": {
    "styles": ["/dist/css/vendors~app-a~app-b.css", "/dist/css/app-a.css"],
    "scripts": ["/dist/js/vendors~app-a~app-b.js", "/dist/js/app-a.js"]
  },
  "app-b": {
    "styles": ["/dist/css/vendors~app-a~app-b.css", "/dist/css/app-b.css"],
    "scripts": ["/dist/js/vendors~app-a~app-b.js", "/dist/js/app-b.js"]
  }
}

generateChunksFiles

boolean = true

Tells the plugin whether to generate the HTML files.

new ChunksWebpackPlugin({
  generateChunksManifest: true
});

This option cancels the main functionality of the plugin and HTML files will not be generated. It can be useful only with addition of generateChunksManifest option for a custom generation of the HTML files.

Caching

The webpack caching feature allows you to generate HTML files that include hash in the filename.

const ChunksWebpackPlugin = require('chunks-webpack-plugin');
const path = require('path');

module.exports = {
  entry: 'main.js',
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.[contenthash].js'
  },
  plugins: [new ChunksWebpackPlugin()]
};

This will generate the following HTML files with hash in the filename.

main-styles.html

<link rel="stylesheet" href="main.72dd90acdd3d4a4a1fd4.css" />

main-scripts.html

<script src="main.72dd90acdd3d4a4a1fd4.js"></script>

Multiple entry points

Example of the webpack configuration with multiple entry points which share common code:

<span class="x x-first x-last">const</span> ChunksWebpackPlugin = require('chunks-webpack-plugin');
const path = require('path');

module.exports = {
  entry: {
    home: 'home.js',
    news: 'news.js'
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: 'bundle.js'
  },
  plugins: [new ChunksWebpackPlugin()]
};

The plugin will generate all files in the ./dist/ directory:

home-styles.html

<link rel="stylesheet" href="vendors~home~news.css" />
<link rel="stylesheet" href="home.css" />

home-scripts.html

<script src="vendors~home~news.js"></script>
<script src="home.js"></script>

news-styles.html

<link rel="stylesheet" href="vendors~home~news.css" />
<link rel="stylesheet" href="news.css" />

news-scripts.html

<script src="vendors~home~news.js"></script>
<script src="news.js"></script>

Contributors