Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"),             "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"     }  
like image 472
ninja dev Avatar asked Sep 14 '17 17:09

ninja dev


People also ask

Can I use variables in .env file?

The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.

Is .env a config file?

In case you are still wondering what all this means, well, you are probably new to the . env file. It's actually a simple configuration text file that is used to define some variables you want to pass into your application's environment. This file needs a something like a parser to make it work.


2 Answers

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); }), 
like image 123
Rameez Rami Avatar answered Sep 21 '22 12:09

Rameez Rami


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)     }) ]  ... 
like image 28
Tyler Liu Avatar answered Sep 17 '22 12:09

Tyler Liu