javascript - ts-node 找不到依赖模块

标签 javascript node.js typescript ts-node

假设有一个包含两个文件的简单 typescript 程序:

src/hello.js

export default function hello() {
  return 'Hello world'
}

src/say.js

import hello from './hello.js'
console.log(hello())

使用以下 tsconfig.json

{
  "compilerOptions": {
    "lib": ["es2023"],
    "module": "node16",
    "target": "es2022",

    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node16",

    "allowSyntheticDefaultImports": true,

    "outDir": "dist",
  },
  "include": ["src/**/*"]
}

以及package.json中设置的CommonJS类型

{
  "type": "commonjs"
}

问题在于 ts-node 失败并出现以下错误:

$ npx ts-node src/say.ts
Error: Cannot find module './hello.js'
Require stack:
- /Users/pawel/wrk/github/ts-sandbox/src/say.ts
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue [as _resolveFilename] (/Users/pawel/wrk/github/ts-sandbox/node_modules/@cspotcode/source-map-support/source-map-support.js:811:30)
    at Function.Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (/Users/pawel/wrk/github/ts-sandbox/src/say.ts:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module.m._compile (/Users/pawel/wrk/github/ts-sandbox/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Object.require.extensions.<computed> [as .ts] (/Users/pawel/wrk/github/ts-sandbox/node_modules/ts-node/src/index.ts:1621:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/Users/pawel/wrk/github/ts-sandbox/src/say.ts' ]
}

当使用 tsc 进行转译并简单地运行 node dist/say.js 时,该项目运行良好。此外,ts-node 替代方案(tsx src/say.tstsimp src/say.ts)也可以正常工作。

请查找完整源代码here .

请问 ts-node 我缺少什么?

最佳答案

只需尝试从导入行中删除 .js 扩展名即可:

src/say.js

import hello from './hello.js' // <<< HERE
console.log(hello())

关于javascript - ts-node 找不到依赖模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77733794/

相关文章:

javascript - 未捕获的 DOMException : Failed to execute 'readAsDataURL' on 'FileReader'

javascript - 循环内的 Jasmine 异步测试未按预期工作

javascript - 使用 NodeJs 和 MongoDB 存储事件的最佳实践是什么

javascript - 使用 .catch 代替 try/catch block

javascript - 使用 Bootstrap 模式的 Ajax 加载

javascript - 未定义的响应,facebook javascript SDK

mysql - Node.js MySQL 错误 : ECONNREFUSED only sometimes

typescript - 未定义的数字(从字符串转换)通过空检查

angular - 将 Angular 添加到窗口类型定义

javascript - 圆圈在 paper.js 的 Canvas 上填充点