How to pass .env file variables to webpack config?

You can use dotenv package for this purpose.

npm install dotenv --save

After installing the package, add this in the top of your config:

const webpack = require('webpack'); // only add this if you don't have yet

// replace accordingly './.env' with the path of your .env file 
require('dotenv').config({ path: './.env' }); 

then in plugins section, add this:

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

Leave a Comment