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 ?
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!
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.
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 %>">
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With