How to pass .env file variables to webpack config?

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"),
            "SECRET_KEY" : "MYSECRETKEYGOESHERE"
        }),

My package.json build script is

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

Answers


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


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,
    }),
    // ...
]

I can't comment to clarify any info so my apologies for the answer.

You could do:

var env = require('.env');

then

new webpack.DefinePlugin({
            "API_URL": JSON.stringify("http://my-api.com"),
            "SECRET_KEY" : "MYSECRETKEYGOESHERE",
            "env_property": env.property
        }),

But I'm making assumptions about your .env file and the way its set up with this answer


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

...

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');

From webpack docs:

The webpack command line environment option --env allows you to pass in as many environment variables as you like. Environment variables will be made accessible in your webpack.config.js. For example, --env.production or --env.NODE_ENV=local (NODE_ENV is conventionally used to define the environment type, see here.)

in your package.json

webpack --env.NODE_ENV=local --env.production --progress

in your webpack.config.js

module.exports = env => {
  // Use env.<YOUR VARIABLE> here:
  console.log('NODE_ENV: ', env.NODE_ENV) // 'local'
  console.log('Production: ', env.production) // true

  return {
    entry: './src/index.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist')
    }

Need Your Help

400 BAD request HTTP error code meaning?

rest http error-handling http-status-code-400

I have a JSON request which I'm posting to a HTTP URL.

What does /p mean in set /p?

windows batch-file abbreviation

What does /p stand for in set /p=? I know that / enables a switch, and I'm fairly sure that I know /a is for arithmetic. I've heard numerous rumours, some saying /p is for prompt, others stating it