【问题标题】:Compile Typescript to native browser ES modules将 Typescript 编译为原生浏览器 ES 模块
【发布时间】:2018-12-31 20:55:39
【问题描述】:

如何编译 Typescript 以与支持 ES modules 的浏览器一起使用?

我在 tsconfig 中使用 <script type="module"> 和 module=es2015,但我无法编写适用于编译器和运行时的导入路径。

浏览器需要完全限定的导入路径和Typescript doesn't convert the import extension during compilation。

例如TS的如下sn-p在编译过程中是不会改变的。

import foo from "./foo.ts";
import bar from "./bar";

当它在浏览器中运行时,它会针对不存在的文件发出两个网络请求。

GET foo.ts -> (should be) GET foo.js
GET bar -> (should be) GET bar.js

【问题讨论】:

标签: typescript tsc es6-modules


【解决方案1】:

目前实现此目的的唯一方法是在您的 TypeScript 导入中使用 .js(即使该文件在技术上是 .ts)。

// index.ts
import foo from "./foo.js";

// foo.ts
export default "foo";

这仅适用于 TypeScript 2 和更现代的版本。有关更多上下文,请参阅此GitHub issue。

【讨论】:

    猜你喜欢
    • 2018-07-06
    • 2021-04-19
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2017-02-13
    • 2020-04-18
    相关资源
    最近更新 更多