Webpack: Bundle.js - Uncaught ReferenceError: process is not defined

Update October 2020:

For webpack 5, you can reference process/browser from the appropriate plugins part of webpack.config.js

// webpack needs to be explicitly required
const webpack = require('webpack')

module.exports = {

/* ... rest of the config here ... */

  plugins: [
    // fix "process is not defined" error:
    // (do "npm install process" before running the build)
    new webpack.ProvidePlugin({
      process: 'process/browser',
    }),
  ]
}

You need to add a plugin to define your env (in webpack config):

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

With dotenv node module:

STEP 1: INSTALL dotenv:

yarn add -D dotenv or npm i -D dotenv

STEP 2: ADD .env file in your project root with the required variables:

NODE_ENV=development
apiKey=w23io222929kdjfk
domain=example.domain.org

STEP 3: DEFINE these variables with webpack.DefinePlugin:

// webpack.config.js
const webpack = require('webpack')
const dotenv = require('dotenv')

// this will update the process.env with environment variables in .env file
dotenv.config();

module.exports = {
  //...
  plugins: [
    // ...
    new webpack.DefinePlugin({
       'process.env': JSON.stringify(process.env)
    })
    // ...
  ]
  //...
}

STEP 4: ACCESS environment variables in your source code:

// src/index.js
alert(process.env.NODE_ENV)
alert(process.env.apiKey)

Important Links:

  • dotenv: https://www.npmjs.com/package/dotenv
  • webpack.DefinePlugin: https://webpack.js.org/plugins/define-plugin/
  • Stackblitz example for dotenv - https://stackblitz.com/edit/node-kdfi4z?file=index.js

Good Luck...


This is how i resolved the

ReferenceError: process is not defined

error with Webpack 5

  1. npm i --save-dev process

  2. Delete the "node_modules" folder

  3. Add const webpack = require('webpack'); at the top of your config file

  4. In your webpack config file, plugin section, add below:

    plugins: [
    new webpack.ProvidePlugin({
        process: 'process/browser',
    }),
    
  5. Also in the webpack add the alias like below:

    resolve: {
     alias: {
         process: "process/browser"
     },
    
  6. Now do npm i

...and when you build your application the error will disappear. you can read about webpck migration [here]