javascript - Typescript 导入在编译为 javascript 时缺少 .js 扩展名
问题描述
我决定将我的 js 项目迁移到 ts 中,但是我面临以下问题:ts 文件中的所有导入都缺少已编译的 js 文件中的 .js 扩展名。这反过来会引发以下错误:
Loading failed for the module with source “http://localhost:5500/build/test/first”.
在我的浏览器控制台上。这是代码
/src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script src="/build/test/last.js" type="module"></script>
</html>
/src/test/first.ts
export class First {
name: string;
constructor(name: string) {
this.name = name
}
}
/src/test/last.ts
import {First} from "./first"
class Last {
constructor() {
let name = new First("this is my name").name;
console.log(name)
}
}
new Last();
/build/test/first.js
export class First {
constructor(name) {
this.name = name;
}
}
/build/test/last.js
import { First } from "./first";
class Last {
constructor() {
let name = new First("this is my name").name;
console.log(name);
}
}
请注意,在 last.js 中,导入缺少 .js 扩展名,如果我手动添加缺少的扩展名,一切都会按预期工作。最后这是我的 ts 配置
{
"compilerOptions": {
"target": "ESNext",
"lib": ["DOM","ES2017", "DOM.Iterable", "ScriptHost"],
"watch": true,
"rootDir": "./src",
"outDir": "./build",
"sourceMap": true,
"removeComments": true,
"noEmitOnError": true,
"strict": true,
}
}
有什么我遗漏的东西没有在导入中添加正确的扩展名吗?如果是这样,请告诉我我做错了什么。谢谢。
解决方案
有什么我遗漏的东西没有在导入中添加正确的扩展名吗?
为什么 TypeScript 会随机更改您的导入?您告诉它导入一个名为的模块./first
,并且它正确地将其编译为一个名为./first
.
如果你想导入一个不同的模块,你需要告诉 TypeScript 导入一个不同的模块。
所以,如果你不想导入一个名为的模块./first
,而是想导入一个名为的模块./first.js
,你需要告诉 TypeScript 导入一个名为的模块./first.js
,而不是一个名为的模块./first
:
import {First} from "./first.js"
推荐阅读
- javascript - 如何从数组中移动所有值但删除最后一个值
- swift - 带有计时器不停止的标签
- elasticsearch - Debian Elasticsearch 插件已安装但未显示
- vue.js - 如何在没有 CLI / Webpack / Node 的情况下制作 Vue 3 应用程序
- php - 你可以在 PHP 中的函数内设置一个常量类属性吗?
- python - 为什么while循环函数不能在这里工作并给我错误
- swift - 如何在 LazyVGrid 中使用 GeometryReader
- node.js - express(NodeJS)有多少个副本?
- c++ - C 和 C++ 中的 Array-in-struct 初始化
- python - 用 pandas 构建指标分形