Tìm kiếm trang web

node.js - Nhập các module từ thư mục gốc của dự án (Node 18 + TS + ESM)


Tôi đang cố gắng nhập một module từ thư mục gốc dự án Node của mình thay vì sử dụng đường dẫn tương đối.
Tôi đang sử dụng Node 18, ESM, Typescript và chạy nó với ts-node-esm.

Mã :

// import { number } from './check.js' // works
import { number } from 'check.js' // does not work

console.log(number)

Lỗi :

~/Code/ts-esm (main)*$ yarn dev
yarn run v1.22.19
ts-node-esm src/start.ts
/home/rjurado/Code/ts-esm/node_modules/ts-node/src/index.ts:843
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/start.ts:2:24 - error TS2307: Cannot find module 'check.js' or its corresponding type declarations.

2 import { number } from 'check.js' // does not work
                         ~~~~~~~~~~

    at createTSError (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/index.ts:843:12)
    at reportTSError (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/index.ts:847:19)
    at getOutput (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/index.ts:1057:36)
    at Object.compile (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/index.ts:1411:41)
    at transformSource (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/esm.ts:400:37)
    at /home/rjurado/Code/ts-esm/node_modules/ts-node/src/esm.ts:278:53
    at async addShortCircuitFlag (/home/rjurado/Code/ts-esm/node_modules/ts-node/src/esm.ts:409:15)
    at async ESMLoader.load (node:internal/modules/esm/loader:431:20)
    at async ESMLoader.moduleProvider (node:internal/modules/esm/loader:350:11)
    at async link (node:internal/modules/esm/module_job:70:21) {
  diagnosticCodes: [ 2307 ]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Tôi đã thêm tùy chọn rootDir vào tsconfig của mình:

{
  "compilerOptions": {
    "lib": [ "es6", "es2021", "es2022" ],
    "module": "ES2022",
    "target": "ES2021",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "rootDir": "./src",
    "outDir": "dist"
  }
}

Làm sao tôi có thể làm điều đó? Tôi đã tạo một ví dụ tối thiểu có thể tái tạo: repo