How to pass webpack environment variables in html?

How can I get / access webpack ENV variables during a process (not runtime in a browser)? webpack.DefinePlugin(...) doesn't seem to work in html files, I don't have access to ENV variables in main index.html

any solution?

+5
source share
2 answers

You can use html-webpack-plugin . You will need to use .ejs or some other template language and then use this as

 new HtmlWebpackPlugin({ template: './src/public/index.ejs', inject: 'body', environment: process.env.NODE_ENV }), 

in index.ejs

 <body class="<%= htmlWebpackPlugin.options.enviornment %>"> 
+6
source

In fact, you can also use variables from DefinePlugin in your ejs template using HtmlWebpackPlugin .

EJS:

 <script async src="https://www.googletagmanager.com/gtag/js?id=<%= GA_TRACKING_ID %>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '<%= GA_TRACKING_ID %>'); </script> 

webpack.config.js:

 new webpack.DefinePlugin({ 'GA_TRACKING_ID': JSON.stringify(process.env.GA_TRACKING_ID), }), 
+2
source

Source: https://habr.com/ru/post/1257815/


All Articles