Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass webpack environment variables in html?

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

any solution ?

like image 248
darkylmnx Avatar asked Oct 06 '16 17:10

darkylmnx


People also ask

Can webpack bundle HTML?

This means Webpack has successfully bundled both our logic from src/index. js and HTML from src/index. html into the dist directory, even automatically linking them together for us. And this is just the beginning of what Webpack can do!

Does webpack use Node_env?

NODE_ENV=production just tells node in what mode to actually run webpack. Meaning, if you have code in your app which does... It will simply leave those in place. In order to make your output code reflect the proper NODE_ENV you have to use either the EnvironmentPlugin or the DefinePlugin.


Video Answer


2 Answers

You can use html-webpack-plugin. You will have to use .ejs or some other template language and then use like that

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

in index.ejs

<body class="<%= htmlWebpackPlugin.options.environment %>"> 
like image 70
mist_dev Avatar answered Oct 13 '22 00:10

mist_dev


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

EJS:

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

webpack.config.js:

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

(You don't have to use process.env, but it'll prevent your app from crashing if the variable isn't defined.)

like image 36
kontrollanten Avatar answered Oct 13 '22 02:10

kontrollanten