Search code examples
javascriptnode.jsbashwebpackdotenv

After I get all variables that inside .env file how to replace the value of any variable of them if it defined in bash or system


In nodejs project if

  • I have index.js file that contains the following
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '/.env') });

console.log(process.env.ENVIRONMENT_VARIABLE);
  • And I have .env file that contains the following
ENVIRONMENT_VARIABLE=a
...and more environment variables
  • And I go to bash and I run the following command
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

  • I have index.js file that contains the following
console.log(process.env.ENVIRONMENT_VARIABLE);
  • And I have .env file same as the previous one ( that in nodejs project )
  • And my webpack configuration as the following
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)
    }),
    ...
  ],
  ...
};
  • And I go to bash and I run the following command
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 is b (which defiend in bash) not a (which defiend in .env file). And if ENVIRONMENT_VARIABLE doesn't defined in bash or system the value that I want to get is a (which defiend in .env file)


Solution

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