Yarn PnP "Cannot find module" - Fix Plug’n’Play Resolution in CI
Yarn Berry’s Plug’n’Play has no node_modules - resolution goes through a .pnp.cjs runtime. A tool launched without that runtime falls back to Node’s default resolver, finds no node_modules, and throws "Cannot find module".
What this error means
Under Yarn PnP, a script or tool fails with Cannot find module '<pkg>' even though the package is installed. Running the same thing via yarn <cmd> (which loads the PnP runtime) works, proving the resolver is the issue.
Error: Cannot find module 'react'
Require stack:
- /app/scripts/build.js
at Function._resolveFilename (node:internal/modules/cjs/loader)
# but 'yarn node scripts/build.js' resolves fineCommon causes
A tool run without the PnP runtime
Invoking node script.js (or a tool directly) does not load .pnp.cjs, so Node’s default resolver looks for a node_modules that PnP does not create.
A tool incompatible with PnP
Some tools assume a node_modules layout and do not support PnP, so they cannot resolve packages even with the runtime present.
How to fix it
Run through yarn so PnP loads
Launch scripts and tools via yarn (or yarn node) so the PnP runtime is active.
# run scripts through yarn's PnP-aware runtime
yarn node scripts/build.js
yarn run build
# generate editor/tool SDKs for PnP support
yarn dlx @yarnpkg/sdksHandle PnP-incompatible tools
- Install Yarn SDKs (
yarn dlx @yarnpkg/sdks) for editor/tool integration. - For a tool that cannot support PnP, set
nodeLinker: node-modulesin.yarnrc.yml. - Always invoke project tooling via
yarnso the runtime is present.
How to prevent it
- Invoke project tooling through
yarn/yarn node. - Generate Yarn SDKs for PnP-aware tooling.
- Use
nodeLinker: node-modulesfor tools that cannot support PnP.