Why TypeScript import CommonJS instead of ESM

Viewed 1572

I followed this tutorial to create a dual package. This is what the package file structure looks like:

my-awesome-lib
  package.json
  dist
  |-- mjs
    |-- package.json
    |-- index.js
  |-- cjs
    |-- package.json
    |-- index.js

In package.json:

  "main": "dist/cjs/index.js",
  "module": "dist/mjs/index.js",
  "exports": {
    ".": {
      "require": "./dist/cjs/index.js",
      "import": "./dist/mjs/index.js"
    }
  },

The package.json in the mjs folder:

{
    "type": "module"
}

The package.json in the cjs folder:

{
    "type": "commonjs"
}

In my Typescript application, I installed my own package, and tried to import it. However, I observed a wierd thing:

// src/index.ts
import { Class } from 'my-awesome-lib'
import { Class } from '../node_modules/my-awesome-lib/dist/mjs/index.js';

The 1st import statement points to the ../node_modules/my-awesome-lib/dist/cjs/index.js instead of the mjs folder. The 2nd import statement is what I actually want.

Can anyone tell me what went wrong? Is it because I published my library in a wrong way?


p.s.

This is my tsconfig.json

{
    "compilerOptions": {
      "target": "es2020",
      "module": "es2020",
      "strict": true,
      "esModuleInterop": true,
      "skipLibCheck": true,
      "forceConsistentCasingInFileNames": true,
      "declaration": true,
      "moduleResolution": "node",
      "outDir": "dist"
    },
    "include": ["src"]
}  

p.s. adding {"type": "module"} to the application's package.json doesn't make this error go away either.

0 Answers
Related