DEV Community

webdiscus
webdiscus

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:

<html>
  <head>
    <!-- include source style -->
    <link href="./style.scss" rel="stylesheet" />
    <!-- include source script -->
    <script src="./main.js" defer="defer"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
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:

<html>
  <head>
    <link
      href="css/style.2a9f3a27.css"
      rel="stylesheet"
      integrity="sha384-gaDmgJjLpipN1Jmuc98geFnDjVqWn1fixlG0Ab90qFyUIJ4ARXlKBsMGumxTSu7E"
      crossorigin="anonymous" />

    <script
      src="js/main.d461fe16.js"
      defer="defer"
      integrity="sha384-E4IoJ3Xutt/6tUVDjvtPwDTTlCfU5oG199UoqWShFCNx6mb4tdpcPLu7sLzNc8Pe"
      crossorigin="anonymous"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Note

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)