The Missing Bit

Using NODE_ENV with typescript and Webpack

NODE_ENV environment variable is commonly used to dictate how to build a javascript app. If it is set to “production”, all debug code should be stripped out.

How to properly use it in Typescript if using Webpack?

I write about this, because the answer is a little bit more subtle than I first thought.

The first step is to use the DefinePlugin in your Webpack config, like so:

new webpack.DefinePlugin({
  'process.env': {
    'NODE_ENV': JSON.stringify(env)
  },
})

Add this entry to the plugins part of your Webpack config.

Now, the “subtle” part is how to declare process.env.NODE_ENV in your Typescript files.

At first, I added the @types/node package and import * as process from "process" . It compiled, but then the Webpack plugin did not do it’s job.

This is because the define plugin only work with global variables that are present “as is” in the source.

The solution, while inelegant, is simple, do not use the @types/node package, do not import the process module and just:

declare var process : {
  env: {
    NODE_ENV: string
  }
}

The Typescript compiler will leave any occurence of process.env.NODE_ENV alone and the define plugin will be able to replace them.