node.js - 使用 tsc 使用 esm 编译 TypeScript 时出现“找不到模块”
问题描述
我有一个package.json
像这样的 esm:
{
"main": "config.js",
"type": "module",
"scripts": {
"start": "npm run build && node ./build/config.js",
"build": "tsc",
...
和一个tsconfig.json
:
{
"compilerOptions": {
"target": "ES2015",
"module": "ES2020",
"strict": true,
"esModuleInterop": true,
"moduleResolution": "node",
"forceConsistentCasingInFileNames": true,
"outDir": "./build"
},
"include": ["./src", "config.ts"],
"exclude": ["./*/**.spec.js"]
}
运行时npm run start
出现以下错误:
> tsc
internal/modules/run_main.js:54
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'F:\Development\test\example\build\src\handlers\index' imported from F:\Development\test\example\build\config.js
at finalizeResolution (internal/modules/esm/resolve.js:277:11)
at moduleResolve (internal/modules/esm/resolve.js:658:10)
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:748:11)
at Loader.resolve (internal/modules/esm/loader.js:97:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:243:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:42:40)
at link (internal/modules/esm/module_job.js:41:36) {
code: 'ERR_MODULE_NOT_FOUND'
我已经尝试将类型更改为 commonjs 和其他配置更改,我做错了什么?
解决方案
显然,即使您使用的是打字稿,我们也需要将导入更改为.js
,因此在我的示例中:
import IndexHandler from "./src/handlers/index";
变为:
import IndexHandler from "./src/handlers/index.js";
。
它不被视为错误,而是 TypeScript 的一部分。
推荐阅读
- android - 无法通过 xml 或以编程方式在 Android Studio 中为 TextView 设置粗体样式
- javascript - 函数访问中的 Javascript 函数
- c# - 将 MS-Project mpp 文件导入 C# .Net Framework 并使用 MPXJ 将数据导出到 SQLite 数据库
- c# - 如何在 asp.net 核心 Web 应用程序中使用 System.Net.Dns.GetHostEntry(ip).HostName 获取用户名?
- python - Python:我收到一个错误,说列表索引超出范围,什么时候不是
- jestjs - 模拟 axios 全部/传播
- flutter - Flutter Firebase:无法更新数据库
- r - 根据前一行加速迭代计算值的循环并排除不符合 R 中标准的行
- javascript - 如何将 ajax response.responseText 设置为全局 JS 变量
- python - 熊猫日期时间转换