Replacing polyfill for process in Webpack v5 from v4

Viewed 2645

I am receiving the following error in Webpack v5 after migrating from v4. I am able to compile my build properly, but performance issue occurs.

Uncaught ReferenceError: process is not defined

Upon checking the documentation it is advised that:

  • 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.

I wish to support frontend and browser usage. What does "use the exports or imports package.json field to use different code depending on the environment" mean?

2 Answers

I think they mean to use the exports and imports fields inside package.json - https://nodejs.org/api/packages.html#packages_exports. I am also trying to wrap my head around it though.

In my case I was able to get around the Uncaught ReferenceError: process is not defined error by adding in my webpack.config.js file the following to the plugins section:

 new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
    'process.env.NODE_DEBUG': JSON.stringify(process.env.NODE_DEBUG),
    'process.type': JSON.stringify(process.type),
    'process.version': JSON.stringify(process.version),
  })

and of course importing webpack: const webpack = require('webpack'); at the very top of the file.

Hope this helps

My error after all the polyfill fix nonsense was "process.versions.node" is undefined. So JSHowTo answer worked for me with one correction:

change 'process.version' to 'process.versions.node'

Related