Typescript编译成功,但node找不到模块



节点错误Error: Cannot find module 'hello',即使Typescript编译成功。

目录结构(注意这与baseUrl的tsconfig docs几乎相同)

main
| src
| ├─ index.ts
| └─ hello
|      └── index.ts
└── tsconfig.json
└── package.json

我只想使用非相对导入(所以没有/,./,../)。我过去遇到过这个问题,并且总是求助于使用相对导入,但我不想继续这样做。

顶层index.ts中有import { helloWorld } from 'hello'

tsc编译成功,输出目录dist如下所示:

main
├─ src
├─ tsconfig.json
├─ package.json
└─ dist
├─ index.js
└─ hello
└── index.js

运行node dist/index.js输出错误Error: Cannot find module 'hello'。import语句从dist/index.js编译到require("hello"),这是抛出错误的地方。

从这个答案来看,如果路径以./开头,require()似乎只会查看当前目录中的模块。因此,当我将其更改为require("./hello")时,它的工作完全正常!

我一直在tsconfig.json中玩baseUrlpaths,但我无法让它输出require("./hello")。真的很感激在这个问题上的一些帮助,并最终得到它的底部,谢谢!

// tsconfig.json
{
"compilerOptions": {
// from extending off "@tsconfig/node16/tsconfig.json"
"lib": ["es2021"],
"module": "commonjs",
"target": "es2021",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
// end of @tsconfig/node16/tsconfig.json
"baseUrl": "src",
"outDir": "dist"
},
"include": ["src"],
"exclude": ["node_modules"]
}

我发现这个话题在Typescript的Github问题中受到了很多关注。关于这个问题的许多问题中的几个:

  • https://github.com/microsoft/TypeScript/issues/26722
  • https://github.com/microsoft/TypeScript/issues/10866

From the TS Lead myself:

我们对此的一般理解是,您应该编写在运行时工作的导入路径,并设置TS标志以满足编译器的模块解析步骤,而不是编写用于TS的开箱操作的导入,然后试图让其他步骤"修复";运行时工作的路径。

所以我们要么使用相对导入,要么使用tsc-alias之类的工具。

最新更新