【问题标题】:Is it possible to es6 import a commonjs module?es6可以导入commonjs模块吗?
【发布时间】:2019-03-14 16:48:44
【问题描述】:

我有一个由 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 未捕获的引用错误:未定义导出 在 countUp.js:13

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

【问题讨论】:

标签: javascript typescript es6-modules


【解决方案1】:

简短回答:否


使用 es6 时,需要使用export 导出,而不是exportsexports 是一个 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>

【讨论】:

  • 所以对 OP 问题的回答很简单:否。
  • 我认为你的答案是否定的。也许你可以改写它。因为问题的全部目的是使用commonjs。我无法更改它的导出方式。
  • 值得澄清(似乎是)OP 的混淆术语。 OP 标题询问 "Is it possible to es6 import a commonjs module?",答案是:取决于 在哪里 完成导入。如果它在 Node.js 中,那么 yes, it's possible,但如果它在浏览器中(这是 OP 在问题正文中所指的内容),那么不,正如您详细说明的那样。
  • 想象 cjs=>esm rollup api import { generate } from 'astring'; export class DurableObjectExample {constructor(el, env){ this.el = el; this.env = env; this.el.blockConcurrencyWhile(async()=&gt; { let stored = await this.el.storage.get("esm"); watcher.on("event", (event) =&gt; { const ast = event.result.cache.modules.ast; const esm = generate(ast); this.el.storage.put("esm", JSON.stringify(esm)) });});}}; 就像一个程序化的 global 命名空间在一个固执己见的只读 self v8 引擎网络工作者,或者一个 durable object
【解决方案2】:

其实你可以使用 module.exports 和 import。它适用于 webpack,也适用于 vs code

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2018-04-13
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    相关资源
    最近更新 更多