In my case, I have many environments to support Ex: .env.local
, .env.dev
, ... etc. I have solved loading environment specific env file to webpack config as follows
Step 1: Create a file for a specific environment - Ex: .env.local
API_HOST=127.0.0.1
API_KEY=mysecretkey
...
Step 2: Create a webpack config common for all environments - webpack.common.js
...
...
const webpack = require('webpack')
const dotenv = require('dotenv')
...
...
module.exports = env => {
return {
resolve: {...},
devServer: {...},
module: {...},
plugins: [
new webpack.DefinePlugin(
{'process.env': JSON.stringify(dotenv.config(path: env.ENV_FILE}).parsed)})
}
}
Here the important thing to be noted is module.exports
should return a function instead of an object so that it can access the env variable (ENV_FILE
in this example) passed on by the environment specific webpack config file, such as webpack.local.js
(step 3).
Step 3: Create a environment specific webpack config file - webpack.local.js
const { merge } = require('webpack-merge')
const common = require('./webpack.common')
module.exports = env => merge(common(env), {
mode: 'development',
output: {
publicPath: 'http://localhost:3000',
},
devtool: 'inline-source-map',
devServer: {
watchFiles: ['src/**/*'],
hot: true,
port: 3000
},
})
In this environment specific file, webpack.common.js file is imported as a function (const common
) that gets called with env
parameter as part of the webpack merge
. Here env
parameter is populated by the --env
option in the webpack
command in the package.json
(step 4)
Step 4: Setup webpack commands in package.json
"scripts": {
"start": "webpack serve --open --env ENV_FILE=.env.local --config webpack.local.js",
"build:prod": "webpack --env ENV_FILE=.env.prod --config webpack.prod.js"
...
}
Here npm command start
serves up a local web server with webpack.local.js
as its webpack config. When the call gets into webpack.local.js
it populates ENV_FILE
key into the env
parameter in the function returned by module.exports
.
Similarly you can setup webpack.prod.js
which can be specific to your prod environment on the lines of webpack.local.js illustrated above.