Reputation: 103
I decided to move my webpack 5 + babel project from require to es6 modules. I added "type: module" to package.json and changed all require to import in my js files
The code builds successfully in production. However, in dev mode I get a browser error "Uncaught ReferenceError: require is not defined" because I excluded node_modules for quick build.
How to solve this problem?
Upvotes: 0
Views: 892
Reputation: 8718
The browser environment doesn't have require
that NodeJS has. And the latter can't really use require
anyway for ESM modules. Your act of excluding node_modules/
from bundling means that those modules aren't actually present in your builds, thus unusable within the browser.
For optimizing the use of external modules in node_modules/
, you can look into cache groups. By default, Webpack 5 should already have a vendor chunk, where all node_modules/
get bundled together into a chunk, e.g. a separate exported file. This already optimizes external bundles as much as possible, since it can be cached between builds (for Webpack in watch mode, that is).
Upvotes: 1