Send environment variables to html with webpack

That's something I spent some time searching for and don't find anything that suits if my requirements. So let's some simple tips.

First is good to remember webpack runs on Nodejs to process html, js, css and bundling also let me explain about my use case, what I need is access Google Analytics and keep a part dev/homolog environment and production environment(.env from this point).

Some solutions I find is declare the variables in CLI when running webpack, but it's far more difficult to configure than using a .env file.

So let's using NodeJS capabilities, first install dotenv for Nodejs, important to say it's different from dotenv-webpack plugin. The next step is declare the import ou require as CJS. (here I'm using Common).

const {parsed} = require('dotenv').config({ path: __dirname + '/.env' });

Using parsed result we can go to next step that's configure the HtmlWebpackPlugin, this plugin allow to send properties.

Now in the webpack configurantion all envs, could be sent to html through HTMLWebpackPlugin without need to declare in the CLI.

new HtmlWebpackPlugin({
  hash: true,
  template: path.resolve(__dirname, 'app/index.html'),
  version: package.version,
  gaTag: parsed.GA_TRACKING_ID,
})

And the property could be accessed as followed

<script async src="https://www.googletagmanager.com/gtag/js?id=<%= htmlWebpackPlugin.options.gaTag %></script>

That's all! I hope this article could help more people.