1
votes

Webpack cannot resolve core Node.js modules

I'm aware that this isn't the only Node.js module query related to Webpack on here, but when applying the solutions that I've read elsewhere, yet another core module seems to be causing another ReferenceError.

I have an index.js file that requires the Crypto module to log a hash to the console:

index.js

const crypto = require('crypto')

const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('I love cupcakes')
                   .digest('hex');
console.log(hash);

When setting up my webpack.congif.js file, I got back this error:

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to:

  • add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
  • install 'crypto-browserify'

After following the above guidance, I got the same error for 'buffer' and 'stream' modules, and to get the config file to compile, I've added fallback statements and installed the relevant modules to cover these missing dependencies:

webpack.config.js

const path = require('path');

module.exports = {
    mode: 'development',
    node: {
        global: true,
    },
    resolve: {
        fallback: { 
            "crypto": require.resolve("crypto-browserify"),
            "buffer": require.resolve("buffer/"),
            "stream": require.resolve("stream-browserify")
        }
    },
    entry: './src/index.js',
    output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
    },
};

Webpack.config now compiles, but when I run index.html in the browser I get the following error in the browser console:

Uncaught ReferenceError: process is not defined

As stated in the 'Breaking Change' error, Webpack 5 no longer polyfills for node core modules, but does this mean that a polyfill is required for every single node module before you can run a node script?

1

1 Answers

0
votes

Try with process/browser polyfill. Put this into your webpack.config.js:

resolve: {
  alias: {
    process: "process/browser"
  },
  ...
}