javascript ts-node找不到依赖模块

30byixjq  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(68)

假设有一个简单的typescript程序,它有两个文件:
src/hello.js

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

字符串
src/say.js

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


使用以下tslog.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.jsts-node替代品(tsx src/say.tstsimp src/say.ts)也可以正常工作。
请找到完整的源代码here
请问我在ts-node中缺少什么?

hiz5n14c

hiz5n14c1#

试着从导入行中删除.js扩展名:
src/say.js

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

字符串

相关问题