Node module included in babel-loader is not defined in Webpack 5

Viewed 292

I need to include a node_module (nanoid) in babel-loader in order to down transpile it to ES5. This used to work in Webpack 4:

module.exports = {
  ...
  module: {
    rules: [
       test: /\.(js|jsx)$/,
       exclude: /node_modules\/(?!nanoid)/,
       loader: 'babel-loader',
    ],
  },
  ...
};

but since I updated to Webpack 5 I get this error in the console:

Uncaught ReferenceError: module is not defined
    at eval (index.js:7)
    at eval (index.js:8)
    at Module../node_modules/nanoid/url-alphabet/index.js (bundle.js:3489)

Webpack throws no error while compiling, but running the bundle in the browser throws the above-mentioned error.

1 Answers

I have the same problem but only when using --hot with webpack-dev-server.

Unfortunately i could not find a fix for that but figured out that the problem seems to be with exports field in package.json of nanoid since version 3.

It seems that some package, webpack?, webpack-dev-server?, others..?, involved in hot loading does not properly resolve the exports field.

I did a downgrade to version 2 of nanoid which is properly resolved and the error disappears.

Related