How do you use variables in the HTML webpack outputs?

Through the use of html-webpack-plugin you can inject variables into the HTML your webpack build generates - no more hardcoding!

Here's how you use it:

First, run yarn add -D html-webpack-plugin or npm install --save-dev html-webpack-plugin

Then, add the following to your webpack config:

/* webpack.config.js */
const HtmlWebpackPlugin = require('html-webpack-plugin');
// rest of your config
plugins: [
    new HtmlWebpackPlugin({
        template: 'index.tmp.html',
        filename: 'index.html',
        templateParameters: {
            some_variable: process.env.SOME_VAR
        },
    }),
]

index.tmp.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title><%= some_variable %></title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

In order for process.env.SOME_VAR to have a variable, you can either use a .env file, or enter the values as part of your CI's configuration (services such as CircleCI and Netlify support this).

Remember that variables injected this way are visible to your users!

Shameless plug

Tired of manually testing your web performance? I'd love to help!

Hi! I'm Max, the developer, designer, and customer support of PerfBeacon.com - a service that automatically runs Google Lighthouse for you (both on a schedule, and via API calls).

Get in touch with me via Twitter or Email.

Be first to know about new features and tips on web performance