How to pass .env file variables to webpack config?

webpack + dotenv

I did get inspiration from the accepted answer, but it doesn't work for me. Maybe the API of dotenv has changed.

The following works for me

import dotenv from 'dotenv'
import { DefinePlugin } from 'webpack'


...

plugins: [
    new DefinePlugin({
      'process.env': JSON.stringify(dotenv.config().parsed)
    })
]

...

You can use dotenv package for this purpose.

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);
}),