Typescript导入在编译为javascript时缺少.js扩展名

问题描述 投票:0回答:1

我已经决定将我的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 config

{
    "compilerOptions": {
        "target": "ESNext",
        "lib": ["DOM","ES2017", "DOM.Iterable", "ScriptHost"],
        "watch": true,
        "rootDir": "./src", 
        "outDir": "./build",
        "sourceMap": true,
        "removeComments": true,
        "noEmitOnError": true,
        "strict": true,
    }
}

我是否缺少未在导入中添加正确扩展名的内容?如果是,请告诉我我做错了什么。谢谢。

javascript typescript ecmascript-6
1个回答
0
投票

我是否缺少未在导入中添加正确扩展名的内容?

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

如果要导入其他模块,则需要告诉TypeScript导入其他模块。

因此,如果您不想导入名为./first的模块,而是想导入名为./first.js的模块,则需要告诉TypeScript导入名为./first.js的模块,而不是名为./first的模块]:

import {First} from "./first.js"
© www.soinside.com 2019 - 2024. All rights reserved.