How to pass .env file variables to webpack config?

Viewed 75993

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"
    } 
7 Answers

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)
    })
]

...

It doesn't match your case exactly (although partially), but I've found this formula to be working best for me.

I use a combination of 2 libs: dotenv to read the .env file for the webpack.config.js (configuration) needs, and webpack-dotenv-plugin for the validation (based on .env.example file) and to pass all the vars from .env file to the application code:

Part of my webpack.config.js:

// this is to load env vars for this config
require('dotenv').config({ // it puts the content to the "process.env" var. System vars are taking precedence
    path: '.env.webpack',
});
// and this to pass env vars to the JS application
const DotenvPlugin = require('webpack-dotenv-plugin');

plugins section:

plugins: [
    // ...
    new DotenvPlugin({ // makes vars available to the application js code
        path: '.env.webpack',
        sample: '.env.webpack.example',
        allowEmptyValues: true,
    }),
    // ...
]

The simplest solution I found is to use this npm package: dotenv-webpack

Create a .env file

// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey

Add it to your Webpack config file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
...
plugins: [
new Dotenv()
]
...
};

Use in your code

// file1.js
console.log(process.env.DB_HOST);
// '127.0.0.1'
Resulting bundle
// bundle.js
console.log('127.0.0.1');

First off...

It appears that you are trying to pass secrets into an angular application.

There is no such thing as a "secret" in client side (browser) javascript!!!

Anything passed into DefinePlugin can be extracted with minimal effort.

Now that we've cleared that up....

Webpack now has the Environment Plugin which makes it a bit easier to pass env variables into the GlobalDefine plugin. From the docs:

new webpack.EnvironmentPlugin(['NODE_ENV', 'DEBUG']);

This is equivalent to the following DefinePlugin application:

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
  'process.env.DEBUG': JSON.stringify(process.env.DEBUG)
});

If you are using dotenv to manage environment vars, you can use the dotenv webpack plugin.

It will only include variables that are referenced in your code, so as long as you don't reference your secrets, they won't be included.

Related