javascript - es6可以导入commonjs模块吗?

标签 javascript typescript es6-modules

我有一个由 Typescript 3.3.3 生成的 commonjs 模块。

是否可以将它与 es6 import 语句一起使用?这是我尝试过的。

生成的模块在文件末尾像这样导出 CountUp:

exports.CountUp = CountUp;

在我的 main.js 中:
import { CountUp } from './js/countUp.js';

在 index.html 中:
  <script src="./js/countUp.js"></script>
  <script src="./main.js" type="module"></script>

但我明白了

countUp.js:13 Uncaught ReferenceError: exports is not defined at countUp.js:13



(注意:countUp.js 现在作为 es6 模块分发)

最佳答案

简短的回答:没有

使用es6时需要使用export导出而不是 exports . exports是一个 commonjs 功能,主要在 node 中使用,而不是 web 浏览器。

如果您想使用 commonjs您需要使用第三方库,例如 requirejs ,但这使用 require()而不是 import , 和 exports而不是 export .然后,您将能够使用带有 typescript 的导入/导出来编写代码,但它将使用 require 进行编译。和 requirejs将处理其余的。

因此,要在浏览器中正确使用它,您可以这样做:

test.js

export function Test() {
  console.log('hello')
}

index.js
import { Test } from './test.js'
Test()

然后,当您在 html 中加载文件时,将执行功能测试。
<script src="index.js" type="module"></script>

关于javascript - es6可以导入commonjs模块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55167994/

相关文章:

javascript - 是入口点,ES6 模块

javascript - 在哪里可以下载 Jtalk 或 Smalltalk for Javascript?

javascript - angular2 在具有自定义可序列化对象的后台线程中工作

angular - 组件上不存在属性

Angular - 单击菜单项后隐藏侧边栏菜单

javascript - javascript/nodejs 中的 require 是否每次在另一个模块中导入时都会执行相同的文件?

javascript - 是否可以通过 cdn 在浏览器中使用 react-select?

javascript - 如何检测 Javascript 正则表达式中的命名空间字符串?

javascript - 触发与 html 分开的表行的表更新 JavaScript 函数?

javascript - jQuery:需要更改特定的列表元素