首页 > 解决方案 > 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,
    }
}

有什么我遗漏的东西没有在导入中添加正确的扩展名吗?如果是这样,请告诉我我做错了什么。谢谢。

标签: javascripttypescriptecmascript-6

解决方案


有什么我遗漏的东西没有在导入中添加正确的扩展名吗?

为什么 TypeScript 会随机更改您的导入?您告诉它导入一个名为的模块./first,并且它正确地将其编译为一个名为./first.

如果你想导入一个不同的模块,你需要告诉 TypeScript 导入一个不同的模块。

所以,如果你不想导入一个名为的模块./first,而是想导入一个名为的模块./first.js,你需要告诉 TypeScript 导入一个名为的模块./first.js,而不是一个名为的模块./first

import {First} from "./first.js"

推荐阅读