首页 > 解决方案 > js 需要导入 .ts 文件而不是 .js

问题描述

我有一个 index.ts 和一个 User.ts 文件

index.ts 文件导入用户:

import User from './User'

然后我使用 tsc 将 ts 文件转换为 js 文件,然后运行索引文件:

tsc index.ts 节点 index.js

不幸的是,这给了我这个错误:

(node:1672) UnhandledPromiseRejectionWarning: C:\temp\dev\models\User.ts:1
(function (exports, require, module, __filename, __dirname) { import {Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn} from "typeorm"
                                                              ^^^^^^

SyntaxError: Unexpected token import

所以似乎我的导入语句import User from './User'被转换为User = require('./User')并仍然导入 User.ts 文件而不是 User.js

标签: typescriptimport

解决方案


TypeScript 编译器不会自动编译你导入的东西——如果这是你想要的东西,你最好使用 Webpack 或 Parcel 之类的东西。要正确编译和导入项目中的所有文件,您必须明确要求tsc这样做。

有两种方法可以做到这一点:

  • 将多个参数传递给tsc- 例如tsc index.ts User.ts
  • 如果.tsconfig目录中有文件,则只需运行tsc即可编译所有.ts文件。请注意,如果您的 中有一个files列表.tsconfig,它只会编译这些文件。

推荐阅读