【问题标题】:Typescript import are missing the .js extension when it compiled to javascript [duplicate]Typescript导入在编译为javascript时缺少.js扩展名[重复]
【发布时间】:2020-09-22 21:38:18
【问题描述】:

我决定将我的 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,
    }
}

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

【问题讨论】:

标签: javascript typescript ecmascript-6


【解决方案1】:

我是否遗漏了未在导入中添加正确扩展的内容?

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

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

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

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

【讨论】:

  • 感谢您的解释!是的,这解决了问题。我相信当我阅读文档 (typescriptlang.org/docs/handbook/modules.html) 时会出现混淆,并且没有提到导入必须以 ts 文件中的 .js 结尾。事实上,他们在模块上的所有示例都没有对 ts 导入进行任何扩展。非常感谢!
  • “没有提到在 ts 文件中导入必须以 .js 结尾”——导入 not.js 结尾是完全可以的。导入只需要是您要导入的东西。真的就是这么简单。如果要导入名为./first 的模块,则编写from "./first",如果要导入名为./first.js 的模块,则编写from "./first.js"。 TypeScript 无法读懂你的想法,它只会导入你告诉它要导入的模块,不多也不少。
  • 在我自己的项目中,我想导入一个名为./config的模块,所以很明显,我导入的是./config而不是./config.js。事实上,在我的项目中,没有 ./config.js,所以这根本行不通。
  • 感谢您的补充说明。
  • 这在使用 jest 进行测试时会破坏。它不允许您使用“./first.js”而不是“./first.ts”
猜你喜欢
  • 2020-04-03
  • 2018-05-10
  • 1970-01-01
  • 2020-10-18
  • 2020-10-12
  • 2017-12-12
  • 2019-10-05
  • 1970-01-01
  • 2019-01-05
相关资源
最近更新 更多