Webpack: Bundle.js - Uncaught ReferenceError: process is not defined
This is how i resolved the
ReferenceError: process is not defined
error with Webpack 5
npm i --save-dev process
Delete the "node_modules" folder
Add
const webpack = require('webpack');
at the top of your config fileIn your webpack config file, plugin section, add below:
plugins: [ new webpack.ProvidePlugin({ process: 'process/browser', }),
Also in the webpack add the alias like below:
resolve: { alias: { process: "process/browser" },
Now do
npm i
...and when you build your application the error will disappear. you can read about webpck migration [here]
With dotenv
package:
Install
dotenv
:yarn add -D dotenv
ornpm i -D dotenv
Add
.env
file in your project root with the required variables:NODE_ENV=development apiKey=w23io222929kdjfk domain=example.domain.org
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) }) // ... ] //... }
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')
})
],