Module not found: Error: Can't resolve "fs" in webpack 5 browser builds
0 reputation · 03 Mar 2022, 01:30 UTC
When webpack 5 targets a browser environment, imports of Node.js core modules such as fs trigger a resolution error if no explicit fallback is configured. This behavior stems from the removal of automatic polyfills for Node.js built-in modules starting in webpack 5, which previously provided implicit shims for node-targeted builds. The presence or absence of a resolve.fallback configuration, along with the target setting (e.g. web, browserslist, or node), determines whether the module resolver succeeds or emits the Module not found: Error: Can't resolve "fs" message. Additionally, adding polyfills for these modules increases bundle size and may not fully emulate the original Node.js API, potentially introducing subtle runtime differences in browser contexts.
- Under what conditions does webpack 5's module resolver treat Node.js core modules as resolvable in browser builds?
- Can resolve.fallback be configured to map fs to a browser-compatible alternative without significantly increasing bundle size?
- What is the recommended strategy for code that conditionally uses Node.js APIs across both Node and browser targets?