【问题标题】:How to run pure typescript project in a browser?如何在浏览器中运行纯打字稿项目?
【发布时间】:2020-08-19 08:47:05
【问题描述】:

我创建了纯打字稿项目,但导入/导出有问题。我在控制台“ReferenceError:未定义导出”中有错误。运行 tsc 命令后,我通过 Visual Studio 代码中的“Go live”扩展打开项目。

这是我的代码:

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["dom", "es2015", "es5", "es6"],
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "esModuleInterop": true
  }
}

index.ts:

import { BoardUI } from './app/BoardUI';
    
const boardUI = new BoardUI();

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>
    <link rel="shortcut icon" href="favicon.png" />
  </head>
  <body>
    <h1>hello</h1>
    <script type="module" src="../dist/index.js"></script>
  </body>
</html>

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    现代浏览器现在原生支持esmodule (esm)。因此,您只需输出 esm 模块即可。请记住,Typescript 将根据您设置的target 输出模块(默认为:es3es3/es5 将输出CommonJS

    总而言之,只需指定 es2015 中的模块即可:

    "module": "es2015",
    

    【讨论】:

    • 现在控制台出现错误:“加载资源失败:服务器响应状态为 404(未找到)BoardUI:1”
    • 我不知道为什么,但 BoardUI.js 文件甚至没有加载到浏览器。
    • 我想我发现了错误。 Typescript 错误将 index.ts 编译为 index.js。错误是导入文件的路径,在 index.js 中路径如下所示:import { BoardUI } from './app/BoardUI';,它应该如下所示:import { BoardUI } from './app/BoardUI.js'; - 它缺少“js”扩展名
    • 我不知道你为什么这么说,因为 tsc 将优先考虑 .ts 文件,并且只允许 .js 文件,因为你在配置中设置了 allowJs: true
    【解决方案2】:

    尝试删除 tsconfig.json 中的 "module": "commonjs",

    否则,您可以将模块更改为ES6,将目标更改为ES2018

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2017-05-28
      • 1970-01-01
      • 2019-02-09
      • 2020-11-03
      • 2021-08-03
      • 2018-10-13
      • 2016-08-14
      • 2023-02-08
      相关资源
      最近更新 更多