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

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]


With dotenv package:

  1. Install dotenv:

    yarn add -D dotenv or npm i -D dotenv

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

    NODE_ENV=development
    apiKey=w23io222929kdjfk
    domain=example.domain.org
    
  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)
        })
        // ...
      ]
      //...
    }
    
  4. Access environment variables in your source code:

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

StackBlitz example: https://stackblitz.com/edit/node-kdfi4z?file=index.js

P.S. for namespaced environment variables check lines 10 - 28 on the StackBlitz page mentioned above.


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')
        })
    ],