Skip to content

Conversation

@Jinjiang
Copy link

Summary

Fixes an issue where vite-plugin-node-polyfills failed to resolve shim imports (like vite-plugin-node-polyfills/shims/process) from packages outside the workspace during the build phase.

Problem

When building a project that imports packages from outside the main workspace (e.g., from a sibling workspace or monorepo package), Rollup would fail with:

[vite]: Rollup failed to resolve import "vite-plugin-node-polyfills/shims/process" from "..."

This issue was reported in the reproduction case: https://github.com/Jinjiang/reproductions/tree/vite-polyfill-20251125

Root Cause

The @rollup/plugin-inject plugin only provides a transform hook but not a resolveId hook. When external packages reference Node.js globals (like process, Buffer, or global), the inject plugin transforms them into import statements:

import process from 'vite-plugin-node-polyfills/shims/process'

However, without a resolveId hook, Rollup cannot resolve these imports when they're in packages outside the main workspace, causing the build to fail.

Solution

Added a custom Rollup plugin called vite-plugin-node-polyfills:shims-resolver that provides a resolveId hook to resolve shim imports. The plugin:

  1. Creates a map of shim import specifiers to their absolute file paths using require.resolve()
  2. Intercepts resolution requests for shim imports
  3. Returns the absolute path to the shim file, ensuring Rollup can properly resolve and bundle them

The fix applies to all three global shims: buffer, global, and process.

Testing

  • ✅ Reproduction case now builds successfully
  • ✅ All unit tests pass (14/14)
  • ✅ All build tests pass (react, vanilla, vue examples)
  • ✅ No regressions introduced

Changes

  • Added shimsResolverPlugin to handle resolveId for shim imports during build
  • The plugin is only created when shims need to be injected (based on globals configuration)
  • Works for both regular Rollup and Rolldown-Vite configurations

Fixes an issue where Rollup failed to resolve shim imports (like
'vite-plugin-node-polyfills/shims/process') from packages located
outside the main workspace during the build phase.

The root cause was that @rollup/plugin-inject only provides a
transform hook but not a resolveId hook. When external packages
reference Node.js globals, the inject plugin transforms them into
import statements, but Rollup couldn't resolve these imports from
cross-workspace packages.

Added a custom Rollup plugin 'vite-plugin-node-polyfills:shims-resolver'
that provides a resolveId hook to properly resolve shim imports by
mapping them to their absolute file paths using require.resolve().

This fix applies to all three global shims: buffer, global, and process.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant