import with Error [ERR_MODULE_NOT_FOUND]: Cannot find module

I looked at the similar questions but couldn’t find solution.

I have a vanilla JS library that I’m testing locally. The library supports both ESM and CommonJS.


Source Code

src/foo/Foo.js

class Foo {}

export {Foo}

src/bar/Bar.js

class Bar {}

export {Bar}

src/index.js (exporting classes)

export { Foo } from "./foo/Foo.js"
export { Bar } from "./bar/Bar.js"

Unit Tests

In my Unit Tests, I encounter [ERR_MODULE_NOT_FOUND] error if I use

test/foo/FooTest.js (preferable using entry point)

import {Foo} from "../../src/index.js"; // doesn't work
import chai from "chai" // is chai the problem?

but works fine if I import Foo directly

import {Foo} from "../../src/foo/Foo.js" // works, and my IDE suggests to use the above short import
import chai from "chai"

I prefer the earlier version since it uses the main entry point.


Package JSON file

package.json

  "name": "mylib",
  "version": "1.0.0",
  "type": "module",
  "main": "bin/cjs/mylib.js",
  "modules": "bin/esm/mylib.js",
  "exports": {
    ".": {
      "import": "./bin/esm/mylib.js",
      "require": "./bin/cjs/mylib.js"
    }
  },