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

Javascriptnode.jsWebpackNode Modules

Javascript Problem Overview


Here's my webpack.config.js

"use strict";

module.exports = {
    entry: ['./main.js'],
    output: { path: __dirname, filename: 'bundle.js' },
    module: {
        loaders: [
            {
                test: /.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                query: {
                    presets: ['es2015', 'react']
                }
            },
            {test: /\.json$/, loader: "json"},
        ]
    },
    externals: {
        React: 'react',
    },
    target: "node",
};

And Main.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
import Chart from 'chartjs';
import jQuery from 'jquery';
import vis from 'vis';
import babel from 'babel-core';

The Bundle.js is inserted in my Index.html. The browser then gives the error:

Uncaught ReferenceError: process is not defined
    at Object.measureMethods (bundle.js:1297)
    at Object.<anonymous> (bundle.js:530)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:288)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:158)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:110)
    at __webpack_require__ (bundle.js:20)
    at Object.<anonymous> (bundle.js:90)

What should I change in the webpack.config.js to make this error go away?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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]

Solution 5 - Javascript

Webpack 5 removes the ability to access environment variables using the notation process.env.MY_ENV_VAR. I had this same problem because I was getting a Uncaught ReferenceError: process is not defined error in my browser console. From the documentation of porting from v4 to v5 of Webpack, they mention the following:

1. Before upgrading to v5, verify that you can easily do it

> Try to set the following options in your webpack 4 configuration and > check if build still works correctly. > > js > module.exports = { > // ... > node: { > Buffer: false, > process: false > } > }; > > > webpack 5 removes these options from the configuration schema and will always use false. > > You have to remove these options again when upgrading your > configuration for webpack 5.

2. Handling env vars because process was removed

> - Regarding Runtime Errors: > - process is not defined. > - webpack 5 does no longer include a polyfill for this Node.js variable. Avoid using it in the frontend code. > - Want to support frontend and browser usage? Use the exports or imports package.json field to use different code depending on the > environment. > - Also use the browser field to support older bundlers,. > - Alternative: Wrap code blocks with the typeof process checks. Note that this will have a negative impact on the bundle size. > - Want to use environment variables with process.env.VARIABLE? You need to use the DefinePlugin or EnvironmentPlugin to define these > variables in the configuration. > - Consider using VARIABLE instead and make sure to check typeof VARIABLE !== 'undefined' too. process.env is Node.js specific > and should be avoided in frontend code.

Therefore, given the above information, it is possible to use environment variables using one of the two plugins below.

const webpack = require("webpack");

module.exports = {
    ...
    plugins: [
        new webpack.DefinePlugin({
            "process.env.MY_ENV_VAR": JSON.stringify(process.env.MY_ENV_VAR)
        }),
        new webpack.EnvironmentPlugin(['MY_ENV_VAR']); // <--This is shorthand, does the same thing as the DefinePlugin
    ],
};

Then in your production code it's still feasable to refer to the environment variable in the same way, example:

console.log(process.env.MY_ENV_VAR);

However, as they said in the documentation included above, using process.env is NOT the recommended way since that is Node.js specific.

Solution 6 - Javascript

Webpack 5, the easiest solution for me...

> npm install dotenv-webpack --save-dev

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

module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Solution 7 - Javascript

To avoid error like denoted in the question I had have provide in webpack.config.js the next configuration (note defining variable level: process.env):

new webpack.DefinePlugin({
                "process.env": JSON.stringify(process.env)
            })

Now it works fine. I'm using webpack 5.30.0, Vue 2.6.12 and vuelidate 0.7.6.

Error I had before in browser console:

Uncaught ReferenceError: process is not defined
    at Object.../node_modules/vuelidate/lib/withParams.js

It is not good thing, that browser client library "vuelidate" requires Node.js specific env variables. Confused build and runtime areas in library.

Solution 8 - Javascript

Having dotenv-webpack/dotenv in your webpack and still doesn't work on Angular? Most probably you're trying to access process.env when running the Angular app on the browser (without Angular Universal), e.g. by ng serve.

Run npm i -S process and then in polyfills.ts paste the code below

import * as process from "process";
window["process"] = process;

Alternatively, if that's not the case and you're looking for webpack to obtain environmental variables then (I don't know why no one suggested yet) dotenv-webpack is the simplest one.

const dotenv = require("dotenv-webpack");
const webpackConfig = {
  plugins: [new dotenv()]
};
module.exports = webpackConfig; // Export all custom Webpack configs.

Of course you need to have them defined in .env file at the root of your project.

Solution 9 - Javascript

Works for me to allow reading env variables inside React, using "webpack": "^5.1.3",

webpack.config.js

const webpackConfig = {
  plugins: [
    new webpack.ProvidePlugin({
      process: 'process/browser',
    }),
    new webpack.DefinePlugin({
      'process.env': JSON.stringify(process.env)
    })
  ],
};

:)

Solution 10 - Javascript

If it is useful for someone:

I tried almost every approach in this thread unsuccessfully. When I went deeper into the problem I realized that what was causing this error on my application was the usage of assert lib:

import * as assert from 'assert';
... 
assert(myVariable !== undefined, "Try to update undefined myVariable ");

BTW: I'm using Angular@~11.2.7

Solution 11 - Javascript

My problem was process is undefined error on internet explorer 11 using webpack 5.

This is how I solved my problem with process.env.MY_ENV_VAR thanks to @ArianPopalyar.
Ref. Answer

In addition to her solution, I added EnvironmentPlugin in webpack.config.js:

...
plugins: [
    new webpack.ProvidePlugin({
        process: 'process/browser'
    }),
    new webpack.EnvironmentPlugin({
        PATH_MODERN: 'dist/modern/domready.min.js',
        PATH_LEGACY: 'dist/legacy/domready.min.js',
        DEBUG: false
    }),
    ...
]

and using it in index.js

if (process.env.PATH_LEGACY) {
    // ...
}

Solution 12 - Javascript

Easy way: prepend the variable "NODE_ENV" when you call webpack i.e. NODE_ENV=production webpack --watch

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncbllView Question on Stackoverflow
Solution 1 - JavascriptFergieView Answer on Stackoverflow
Solution 2 - JavascriptKinnzaView Answer on Stackoverflow
Solution 3 - JavascriptAakashView Answer on Stackoverflow
Solution 4 - JavascriptArian PopalyarView Answer on Stackoverflow
Solution 5 - JavascriptroundtheworldView Answer on Stackoverflow
Solution 6 - JavascriptAlmedin HodžićView Answer on Stackoverflow
Solution 7 - JavascriptYan PakView Answer on Stackoverflow
Solution 8 - JavascriptDaniel DanieleckiView Answer on Stackoverflow
Solution 9 - JavascriptEmanuelView Answer on Stackoverflow
Solution 10 - JavascriptLukasavicusView Answer on Stackoverflow
Solution 11 - JavascriptMuhammedView Answer on Stackoverflow
Solution 12 - JavascriptBigCloudView Answer on Stackoverflow