How to pass .env file variables to webpack config?

ninja dev picture ninja dev · Sep 14, 2017 · Viewed 35.2k times · Source

I am new to webpack and worked out almost all build sections, but now the problem is that I want to pass the environment variables from a .env file to webpack config, so that I can pass that variables to my build files via webpack.DefinePlugin plugin.

Currently I am able to to pass environment variable directly from webpack to to my build. Please see the code below which I used in webpack.

new webpack.DefinePlugin({
            "API_URL": JSON.stringify("http://my-api.com"),
            "FRONT_END_API_KEY" : "MYFRONTENDKEYGOESHERE"
        }),

My package.json build script is

"scripts": {
    "start": "NODE_ENV=development webpack-dev-server --progress --port 8000 --content-base app/build/src"
    } 

Answer

Rameez Rami picture Rameez Rami · Sep 15, 2017

You can use dotenv package for this purpose

Reference: https://www.npmjs.com/package/dotenv https://github.com/motdotla/dotenv

At top of webpack config file, require dotenv as follows(set your .env path currectly)

var dotenv = require('dotenv').config({path: __dirname + '/.env'});

in webpack config plugins section use

new webpack.DefinePlugin({
            "process.env": dotenv.parsed
        }),

Now you can use the env variables throughout your app. try console.log(process.env); in you app code