Clue Mediator

How to pass webpack environment variables in HTML

๐Ÿ“…March 17, 2021
๐Ÿ—ReactJS

Today we will show you how to pass webpack environment variables in HTML.

Letโ€™s assume that you have created the react application using the webpack and you want to pass the environment variables in the HTML file so you can use the html-webpack-plugin npm plugin to inject the variable to the HTML file.

If you are using the `webpack.DefinePlugin(...)` then you can directly access it in the HTML file with minor changes.

Use the following code snippets to access the variables in the HTML file.

new webpack.DefinePlugin({
  "foo": JSON.stringify("bar"),
  "bodyText": JSON.stringify("This is testing text.")
}),
new HtmlWebpackPlugin({
  inject: true,
  template: './public/index.html'
})

Try to exclude the `.html` by setting the `exclude` option.

{
  test: /\.html$/,
  loader: 'html-loader',
  exclude: /\.html$/
}

Your config file should look like below.

webpack.config.js

// ...
// ...
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  // ...
  module: {
    rules: [
      {
        test: /\.html$/,
        loader: 'html-loader',
        exclude: /\.html$/
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      "foo": JSON.stringify("bar"),
      "bodyText": JSON.stringify("This is testing text.")
    }),
    new HtmlWebpackPlugin({
      inject: true,
      template: './public/index.html'
    })
  ]
}

Once you have made all the above configurations in the `webpack.config.js` file, we can use the following syntax (`<%= foo %>`) in the HTML file to access the variables.





  <meta charset="utf-8">
  <title><%= foo %></title>



  <div><%= bodyText %></div>
  <div id="root"></div>

Only these changes are required to access the env variables in the HTML file.
Thank you for reading. Happy Coding..!! ๐Ÿ™‚