darkylmnx
darkylmnx

Reputation: 2071

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 ?

Upvotes: 40

Views: 33062

Answers (2)

mist_dev
mist_dev

Reputation: 686

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 %>">

Upvotes: 53

kontrollanten
kontrollanten

Reputation: 2829

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.)

Upvotes: 34

Related Questions