DEV Community


Posted on • Updated on

Auto generate integrity attribute for script and style tags in HTML using Webpack

What is integrity hash?

The subresource integrity hash is a cryptographic value of the integrity attribute that used by a browser to verify that the content of an asset has not been manipulated. If the asset has been manipulated, the browser will never load it.

The integrity attribute can be used with the script and link tags.

Webpack plugin

You need to install the html-bundler-webpack-plugin:

npm install html-bundler-webpack-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode

The Bundler Plugin generate the integrity hashes and adds the integrity attribute to the link and script tags when generating HTML.

For example, we have a simple HTML template with a script and a style:

    <!-- include source style -->
    <link href="./style.scss" rel="stylesheet" />
    <!-- include source script -->
    <script src="./main.js" defer="defer"></script>
    <h1>Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode

The Webpack config:

const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  output: {
    // required for subresource integrity to work
    crossOriginLoading: 'anonymous',
  plugins: [
    // renders templates and injects integrity hash
    new HtmlBundlerPlugin({
      entry: {
        // template where are included link and script tags
        index: 'src/views/index.html',
      js: {
        // the JS filename must contains a contenthash
        filename: 'js/[name].[contenthash:8].js',
      css: {
        // the CSS filename must contains a contenthash
        filename: 'css/[name].[contenthash:8].js',
      // include `integrity` attribute in production mode only
      integrity: 'auto',
Enter fullscreen mode Exit fullscreen mode

The generated HTML file dist/index.html contains the integrity hashes:

      crossorigin="anonymous" />

    <h1>Hello World!</h1>
Enter fullscreen mode Exit fullscreen mode


The integrity hash is generated when using webpack build in the production mode.
When using webpack watch or serve, no hashes will be generated because it doesn't make sense.

View in browser

Open in StackBlitz

Open generated dist/index.html. The link and script tags will contain the integrity attribute with a hash.

Give HTML Bundler Plugin for Webpack a ⭐️ on GitHub

Top comments (0)