How to pass webpack environment variables in HTML
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.
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 | { test: /\.html$/, loader: 'html-loader', exclude: /\.html$/ } |
Your config file should look like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // ... // ... 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' }) ] } |
webpack.config.js
file, we can use the following syntax (<%= foo %>
) in the HTML file to access the variables.1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title><%= foo %></title> </head> <body> <div><%= bodyText %></div> <div id="root"></div> </body> </html> |
Only these changes are required to access the env variables in the HTML file.
Thank you for reading. Happy Coding..!! 🙂