'How to forbid replacing process.env variables during compilation in webpack?

Story

I'm developing the AWS Lambda functions and compile the code using webpack.

I've read some of the articles and it seems that the process.env variables are auto replaced during compilation. Although it's cool I want to forbid this behaviour.

Why?

Because I'm passing environment variables using AWS Lambda dashboard.

Webpack configuration

const nodeExternals = require('webpack-node-externals')
const webpack = require('webpack')
const path = require('path')

module.exports = {
  target: 'node',
  entry: path.resolve(__dirname, 'index.ts'),
  externals: [nodeExternals()],
  devtool: 'inline-source-map',
  mode: 'production',
  module: {
    rules: [{
      test: /\.tsx?$/,
      use: [{
        loader: 'ts-loader',
        options: {
          experimentalWatchApi: true,
        },
      }],
    }]
  },
  plugins: [],
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  output: {
    filename: 'index.js',
    libraryTarget: 'commonjs',
    path: path.resolve(__dirname, 'dist')
  }
}

Question

Is it possible to forbid the behaviour of replacing the process.env variables during webpack compilation? If yes please help me to achieve this effect.



Solution 1:[1]

mode option in Webpack configuration enables the replacement of process.env.NODE_ENV:

development

Sets process.env.NODE_ENV on DefinePlugin to value development. Enables NamedChunksPlugin and NamedModulesPlugin.

production

Sets process.env.NODE_ENV on DefinePlugin to value production. Enables FlagDependencyUsagePlugin, FlagIncludedChunksPlugin, ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin, SideEffectsFlagPlugin and TerserPlugin.

none

Opts out of any default optimization options

So does webpack -p CLI option.

In case, the effect of DefinePlugin on process.env.NODE_ENV is not desirable, listed plugins should be applied without DefinePlugin, as the documentation shows for production and development modes.

Solution 2:[2]

Set optimization.nodeEnv to false

From:

https://webpack.js.org/configuration/optimization/#optimizationnodeenv

optimization.nodeEnv

boolean = false string

Tells webpack to set process.env.NODE_ENV to a given string value. optimization.nodeEnv > uses DefinePlugin unless set to false. optimization.nodeEnv defaults to mode if set, > else falls back to 'production'.

Solution 3:[3]

While setting optimization.nodeEnv to false works for the NODE_ENV variable, it doesn't work for all environment variables, and it doesn't prevent process.env from being replaced in the compiled code.

I'm working with Webpack on the backend, so having access during runtime is important.

Since there doesn't seem to be an official way of preserving process.env in the compiled code, I found this workaround, which worked for me.

I had to define a new global variable, which I called ENVIRONMENT, that will be replaced with process.env during compilation.

new webpack.DefinePlugin({
  ENVIRONMENT: 'process.env',
}),

In my code, I would then access it like a regular object:

ENVIRONMENT.DATABASE_URL

The above compiles to process.env.DATABASE_URL.

Solution 4:[4]

I was able to avoid this behavior in my vue.config.js by adding:

const Config = require('webpack-chain');
const config = new Config();
module.exports = {
  chainWebpack: config => {
    config.plugins.delete("define")
  },
  configureWebpack: {
  ...,
  },
  .....
}

Solution 5:[5]

I bumped on the same issue with webpack replacing process.env varibles at build time. For a SSR application this is not the wanted behavior.

As a workaround I managed to fool webpack by using something like this in my code:

process['e' + 'nv'].MY_VARIABLE

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil
Solution 2 tepez
Solution 3 Felix
Solution 4 Lord-Y
Solution 5 raduB