unjs / unbuild

📦 A unified JavaScript build system
MIT License
2.35k stars 90 forks source link

Error: Directory import '...' is not supported resolving ES modules imported #444

Closed varugasu closed 6 days ago

varugasu commented 6 days ago

Environment

yarn@1.22.22 node@v20.11.0

Reproduction

Describe the bug

I have an issue with the output from unbuild with vitest with the following error:

 FAIL  src/component.test.tsx [ src/component.test.tsx ]
Error: Directory import '/Users/vargasmesh/Projects/Git/varugasu/reproduction-bundle-bug/node_modules/@mui/material/Button' is not supported resolving ES modules imported from /Users/vargasmesh/Projects/Git/varugasu/reproduction-bundle-bug/node_modules/@varugasu/reproduction-lib/dist/components/button/index.mjs
Did you mean to import @mui/material/node/Button/index.js?

To reproduce it, I created this library and published to GitHub packages: https://github.com/varugasu/reproduction-lib This library uses unbuild and one thing that I am doing is to preserve the folder structure by following Rollup instructions using glob: https://rollupjs.org/configuration-options/#input

I also created this project: https://github.com/varugasu/reproduction-bundle-bug This project imports the @varugasu/reproduction-lib package. I can normally run in dev mode and build, but when I execute yarn test it breaks

Additional context

No response

Logs

No response

varugasu commented 6 days ago

This seems to be related on how Vitest resolves dependency. See https://github.com/vitest-dev/vitest/discussions/4233 for more information.

Based on @sheremet-va reply (https://github.com/vitest-dev/vitest/discussions/4233#discussioncomment-7179094):

Vitest has to use Node.js resolution so you don't have multiple instances of the same package, and Node.js doesn't support module field.

After reading https://nodejs.org/api/packages.html#package-entry-points I saw we have node option:

"node" - matches for any Node.js environment. Can be a CommonJS or ES module file. In most cases explicitly calling out the Node.js platform is not necessary.

Based on this, I changed the package.json to:

  "exports": {
    "./*": {
      "types": "./dist/*/index.d.ts",
      "node": "./dist/*/index.cjs",
      "import": "./dist/*/index.mjs",
      "require": "./dist/*/index.cjs"
    }
  },

Therefore, to solve this issue we need the line "node": "./dist/*/index.cjs" on exports

On my @varugasu/reproduction-lib the version 1.0.1 is broken. But I created 1.0.2-fix that if we run yarn test with it, it passes.