javascript 导入中缺少Typescript转译代码“*.js”

yi0zb3m4  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(85)

我有以下代码(示例):
User.ts

...
import { UserFavoriteRoom } from "./UserFavoriteRoom.js";
import { Room } from "./Room.js";
import { Reservation } from "./Reservation.js";
import { Message } from "./Message.js";
import { Review } from "./Review.js";
...

字符串
但是当typescript将代码转译为JavaScript时,结果看起来像这样:
User.js

...
import { UserFavoriteRoom } from "./UserFavoriteRoom";
import { Room } from "./Room";
import { Reservation } from "./Reservation";
import { Message } from "./Message";
import { Review } from "./Review";
...


正如你所看到的,.js在导入中丢失了,这是一个巨大的问题,因为当我尝试运行代码时,会发生这种情况:

'Error [ERR_MODULE_NOT_FOUND]: Cannot find module: 'UserFavoriteRoom' imported from User.js


例如,如果我手动将.js附加到userFavoriteRoom(User.js文件中的导入),那么错误就会消失,并且在导入结束时没有.js的另一个导入会发生类似的错误。
下面是我的tsconfig.json:

{
  "compilerOptions": {
    "rootDirs": [
      "src"
    ],
    "outDir": "dist",
    "lib": [
      "es2020",
      "esnext.asynciterable"
    ],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": [
      "node"
    ],
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
  },
}


和我的包。json:(我使用的是node 18.16.0)

{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "build": "tsc --build tsconfig.json",
    "start": "npm run build && node ./dist/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module",
  "dependencies": {
    "@apollo/server": "^4.7.5",
    "class-validator": "^0.14.0",
    "graphql": "^16.7.1",
    "mysql": "^2.18.1",
    "reflect-metadata": "^0.1.13",
    "type-graphql": "^2.0.0-beta.2",
    "typeorm": "^0.3.17"
  },
  "devDependencies": {
    "@types/node": "^20.4.2",
    "typescript": "^5.1.6"
  }
}


我可以做什么来自动将.js附加到编译代码中的导入?

ff29svar

ff29svar1#

尝试将allowJs编译器标志添加到Typescript配置中:

{
  "compilerOptions": {
    // ...
    "allowJs": true
  },
}

字符串
文档:https://www.typescriptlang.org/tsconfig#allowJs

相关问题