cbll
cbll

Reputation: 7219

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

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?

Upvotes: 114

Views: 201436

Answers (15)

amigobrewbrew
amigobrewbrew

Reputation: 1

In my case this issue was caused because I started using webpack/vite bundlers for my existing firebase project. Initially 'firebase deploy' was mapped to the 'build' folder and I had to change it to 'dist' folder in 'firebase.json'. Else 'firebase deploy' kept deploying my old builds which had code that relied on deps that I already had uninstalled. Which somehow gave me the blank page with 'process is not defined' error.

Upvotes: 0

Maxim Secret
Maxim Secret

Reputation: 31

it works for me - webpack 5:

const NODE_ENV = process.env.NODE_ENV || (BRANCH === 'master' ? 'production' : 'develop')
const WEBPACK_ENV = {
    PORT: `"${PORT}"`,
    // NODE_ENV: `"${NODE_ENV}"`,
    // ...other variables
};
// webpack config module:
resolve: {
    fallback: {
        process: require.resolve('process/browser'),
    },
},
plugins: [
    new webpack.DefinePlugin({
        'process.env': WEBPACK_ENV,
    }),
    new webpack.ProvidePlugin({
        process: 'process/browser',
    }),
],
optimization: {
    nodeEnv: `"${NODE_ENV}"`,
},

Upvotes: -1

Conrad S
Conrad S

Reputation: 354

One obvious thing to check if you're sure you've properly set up dotenv or some other way to inject the environment variables, is that you are actually referencing the correct environment variable in your browser-side code! For example even if

process.env.ENVIRONMENT

is properly defined, you would get the above error for writing:

process.env.EENVIRONMENT

(note the misspelling)

This stumped me because I was expecting to get an error related to process.env.EENVIRONMENT being undefined, instead of process, but of course webpack is totally replacing process.env.ENVIRONMENT with a value, not creating a process.env object that can be referred to elsewhere.

Upvotes: 1

Karolis Vaitkevicius
Karolis Vaitkevicius

Reputation: 340

For anyone still struggling with this here's something you could try:

Replace the process/browser with process or process/browser.js

    new webpack.ProvidePlugin({
      process: 'process'
    })

With webpack 5 and ES6 modules I think there's some difficulty in package resolution here, which is why we need a better path for the process.

Otherwise try including this in your webpack.config:

  resolve: {
    fallback: {
      'process/browser': false,
    }
  },

This can work to overcome the error, but not sure if it doesn't actually break the place where it's being used. In my case the first suggestion worked out.

Upvotes: 0

Fergie
Fergie

Reputation: 6245

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')
// import webpack from 'webpack' // (if you're using ESM)

module.exports = {

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

  plugins: [
    // fix "process is not defined" error:
    new webpack.ProvidePlugin({
      process: 'process/browser',
    }),
  ]
}

Then run

npm install process

before building.

Upvotes: 152

Aakash
Aakash

Reputation: 23855

For namespaced environment variables (more secure) check lines 10 - 28 on this StackBlitz page.

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

Upvotes: 53

Lukasavicus
Lukasavicus

Reputation: 154

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

Upvotes: 1

Arian Al Lami
Arian Al Lami

Reputation: 937

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]

Upvotes: 46

Emanuel
Emanuel

Reputation: 3277

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

:)

Upvotes: 4

Muhammed
Muhammed

Reputation: 164

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) {
    // ...
}

Upvotes: 0

Yan Pak
Yan Pak

Reputation: 1867

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.

Upvotes: 4

Almedin Hodžić
Almedin Hodžić

Reputation: 493

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()
  ]
  ...
};

Upvotes: 4

roundtheworld
roundtheworld

Reputation: 2795

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.

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.

Upvotes: 23

Daniel Danielecki
Daniel Danielecki

Reputation: 10590

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.

Upvotes: 3

Kinnza
Kinnza

Reputation: 1301

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

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

Upvotes: 41

Related Questions