[Bug?]: ERR_MODULE_NOT_FOUND when trying to run a package with a .mjs bin
Self-service
- [X] I'd be willing to implement a fix
Describe the bug
Trying to run Husky on Yarn 4.x fails if I don't use the node-modules linker with the following error:
node:internal/process/esm_loader:40
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/xxx/.yarn/berry/cache/husky-npm-9.0.10-93b6062488-10c0.zip/node_modules/husky/bin.mjs' imported from /home/xxx/Repos/xxx/xxx/
Did you mean to import /home/xxx/.yarn/berry/cache/husky-npm-9.0.10-93b6062488-10c0.zip/node_modules/husky/bin.mjs?
at new NodeError (node:internal/errors:405:5)
at finalizeResolution (node:internal/modules/esm/resolve:327:11)
at moduleResolve (node:internal/modules/esm/resolve:980:10)
at defaultResolve (node:internal/modules/esm/resolve:1193:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:403:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:372:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:249:38)
at ModuleLoader.import (node:internal/modules/esm/loader:335:34)
at node:internal/modules/run_main:92:28
at loadESM (node:internal/process/esm_loader:34:13) {
url: 'file:///home/xxx/.yarn/berry/cache/husky-npm-9.0.10-93b6062488-10c0.zip/node_modules/husky/bin.mjs',
code: 'ERR_MODULE_NOT_FOUND'
}
So far as I can tell it started occurring when they moved from bin.js to bin.mjs but I don't know much about this at all.
Originally reported at: https://github.com/typicode/husky/issues/1390
To reproduce
yarn set version 4.1.0
yarn add husky
yarn husky
Environment
System:
OS: Linux 5.15 Ubuntu 22.04.3 LTS 22.04.3 LTS (Jammy Jellyfish)
CPU: (6) x64 AMD Ryzen 5 5600X 6-Core Processor
Binaries:
Node: 20.11.0 - /tmp/xfs-4ee14e1a/node
Yarn: 4.1.0 - /tmp/xfs-4ee14e1a/yarn
npm: 10.2.4 - ~/.local/share/mise/installs/node/lts/bin/npm
Additional context
This is on WSL2, not sure if that is relevant at all. I've reproduced it on Node 18 as well.
To be clear, this works fine with Yarn 1.x or with the node-modules linker enabled.
have you used yarn pnp?
Yes, all defaults - nothing in .yarnrc.yml at all.
Yes, all defaults - nothing in .yarnrc.yml at all.
I have similar issue when use babel loader, and it's caused by an 'import(xxx)' in a cjs file
https://github.com/babel/babel-loader/issues/1015
In this case, yarn is unable to automatically determine the ESM loader is needed. You need to force it by setting pnpEnableEsmLoader.