In nodejs project if
index.js
file that contains the followingconst path = require('path');
require('dotenv').config({ path: path.join(__dirname, '/.env') });
console.log(process.env.ENVIRONMENT_VARIABLE);
.env
file that contains the followingENVIRONMENT_VARIABLE=a
...and more environment variables
export ENVIRONMENT_VARIABLE=b && node ./index.js
The value of ENVIRONMENT_VARIABLE
that I will get after I run app is b
(which defiend in bash)
But in webpack project if
index.js
file that contains the followingconsole.log(process.env.ENVIRONMENT_VARIABLE);
.env
file same as the previous one ( that in nodejs project )const path = require('path');
const webpack = require('webpack');
const dotenv = require('dotenv').config({ path: path.join(__dirname, '/.env') });
module.exports = {
...
entry: path.join(__dirname, '/index.js'),
...
plugins: [
...
new webpack.DefinePlugin({
'process.env': JSON.stringify(dotenv.parsed)
}),
...
],
...
};
export ENVIRONMENT_VARIABLE=b && yarn start
The value of ENVIRONMENT_VARIABLE
that I will get after I run app is a
(which defiend in .env
file) not b
(which defiend in bash)
But the value of
ENVIRONMENT_VARIABLE
that I want to get isb
(which defiend in bash) nota
(which defiend in.env
file). And ifENVIRONMENT_VARIABLE
doesn't defined in bash or system the value that I want to get isa
(which defiend in.env
file)
parsed
that is returned by dotenv.config
is what was loaded from your path
(.env
) and does not take into account what's already in your environment (i.e. process.env
). The config
method assigns to process.env
based on parsed
(but will not override).
Passing only the variables you intended to use in Webpack from process.env
should fix your issue:
new webpack.DefinePlugin({
'process.env.ENVIRONMENT_VARIABLE': JSON.stringify(process.env.ENVIRONMENT_VARIABLE)
})