Environment variables in Typescript with Webpack

create-react-app environment variables should be prefixed with REACT_APP_:

Note: You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

from the "Adding Custom Environment Variables" documentation.

You should be adding these environment variables to your .env file(s) in place of adding these to your .bash_profile file. The appropriate file will be picked up depending on the build (i.e. start or build), and the application will be easier to share and deploy.


The way I do it is to have a .env file(add it to .gitignore) in the root of my project files.

Within that file I define my project environment variables(additional variables can be separated by adding each to it's own line):

NODE_ENV=development

Then using the dotenv npm module I can access the values in any webpack file(or server side expressJS file for example).

// in the command line
$ npm install --save dotenv

// at the top of the webpack config file
require('dotenv').config();

// in the plugins of the webpack config
plugins: [
    new webpack.DefinePlugin({
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
    })
],

Now I can reference it within my app being transpiled by webpack:

console.log(NODE_ENV); // development

The other answers require create-react-app so I will offer mine.

First, add the plugin to your Webpack configuration:

const webpack = require("webpack");

module.exports = {
  // ... 
  plugins: [
    new webpack.DefinePlugin({
      MY_ENV_VAR: JSON.stringify(true),
    }),
  ],
};

Next, declare the variable in TypeScript:

declare var MY_ENV_VAR : string | undefined;

Finally, you can access the variable in your code:

console.log(MY_ENV_VAR);