【问题标题】:TypeScript import doesn't work after compiling to JavaScript编译为 JavaScript 后 TypeScript 导入不起作用
【发布时间】:2021-04-15 05:53:35
【问题描述】:

起始页.ts

export function startingPage () {...rest of function}

main.ts

import { startingPage } from "./starting-page";

startingPage();

index.html

<script src="/dist/main.js" type="text/javascript"></script>

错误:

 Uncaught SyntaxError: Cannot use import statement outside a module                         main.js:1

说明

我想它不起作用,因为在 JS 文件中它应该是 module.exports = startingPage; 就像在我以前的 vanilla JS 项目中一样,它工作得很好,但是它是 TS 项目,我不知道如何使它工作。 edit: 显然,我将其导入为 const startingPage = requrie('...')

【问题讨论】:

  • 你用什么来编译打字稿?
  • 我正在运行 tsc 命令,虽然我可能已经找到了解决问题的方法,但我当然需要对此进行确认。在另一个项目中,我使用 Parcel 进行项目构建,我的问题是否可能是,我在页面端脚本上使用节点端“require”,而不使用 webpack(我认为 Parcel 涉及) ?编辑:我还从 ts.config 中删除了模块:'commonjs',因为我的目标是 es6,而不是默认的 es5
  • 我对所有这些都非常陌生,所以如果我让您更难以理解,我深表歉意
  • 包裹使用 Babel 而不是 webpack
  • 您需要将type="module" 添加到您的&lt;script&gt; 标签中

标签: javascript typescript import export es6-modules


【解决方案1】:

我的问题的解决方案是安装 Parcel - 应用程序捆绑器。

正如我提到的,我在我的 vanilla JS 项目中使用了它,所以我现在也尝试了它,它工作得很好。与其说是 TS 项目构建问题,不如说是 JS 语法错误。

【讨论】:

  • 很高兴您找到了解决方案
猜你喜欢
  • 2020-02-15
  • 2018-09-08
  • 2020-08-07
  • 2019-11-14
  • 2017-02-08
  • 2017-03-11
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
相关资源
最近更新 更多