typescript - 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
解决方案
TypeScript 编译器不会自动编译你导入的东西——如果这是你想要的东西,你最好使用 Webpack 或 Parcel 之类的东西。要正确编译和导入项目中的所有文件,您必须明确要求tsc
这样做。
有两种方法可以做到这一点:
- 将多个参数传递给
tsc
- 例如tsc index.ts User.ts
。 - 如果
.tsconfig
目录中有文件,则只需运行tsc
即可编译所有.ts
文件。请注意,如果您的 中有一个files
列表.tsconfig
,它只会编译这些文件。
推荐阅读
- android - 手游、跨平台排行榜/挑战
- php - 如何在使用 Ultimate 会员插件在 Wordpress 中提交之前删除输入值
- javascript - 从 ES6 中的模块调用函数
- c# - 从 C# 运行时如何隐藏 DisplaySwitch.exe 侧边栏
- bash - 在 shell 脚本中同时发出 http 请求并将响应保存到变量中而不写入文件
- c - 测量通过 C 中的套接字发送文件的时间
- angular - 角路由器链接和点击事件触发器
- android - 如何根据平台隐藏 AppBar 后退按钮?
- spring-boot - Spring Boot JPA - 按 2 列查找
- c++ - 当我的路径不知道时如何提取文件名?