我正在尝试让 Nest.JS 项目使用 ES2022,因为我正在尝试使用 ES 模块包。我已经更新了
tsconfig.json
和 paackage.json
但它不起作用,因为它不断出现此错误。
node:internal/modules/esm/resolve:257
throw new ERR_MODULE_NOT_FOUND(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\CodeGhinux\Desktop\project\Forked\project-core\dist\src\app.module' imported from C:\Users\CodeGhinux\Desktop\project\Forked\project-core\dist\src\main.js
at finalizeResolution (node:internal/modules/esm/resolve:257:11)
at moduleResolve (node:internal/modules/esm/resolve:914:10)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:554:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:523:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49) {
code: 'ERR_MODULE_NOT_FOUND',
url: 'file:///C:/Users/CodeGhinux/Desktop/project/Forked/project-core/dist/src/app.module'
}
Node.js v22.8.0
[11:46:59] Found 0 errors. Watching for file changes.
我还在
"type": "module"
中添加了 package.json
并更新了我的 tsconfig.json
以包含 ES2022 模块。我也尝试过使用EsNext
,但它仍然给出相同的错误。
这是我现在的
tsconfig.json
{
"compilerOptions": {
"module": "ES2022",
"moduleResolution": "bundler",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2022",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"esModuleInterop": true,
"lib": ["ES2022"]
},
"exclude": ["node_modules"],
"include": ["src/**/*.ts", "bin/*.ts"]
}
导入语句的相对说明符必须使用文件扩展名:https://nodejs.org/api/esm.html#esm_import_specifiers
只是
import {HelloWorld} from "./HelloWorld.js"
; TypeScript 足够聪明,可以在编译期间找出你想要的 HelloWorld.ts。
解决方法可能是https://www.npmjs.com/package/tsc-alias,如https://stackoverflow.com/a/76678279/517319
中所述