如何在ES6模块节点应用程序中包含commonjs模块? [英] How to include commonjs module in ES6 module node app?
问题描述
我有一个要以标准ES6模块格式使用的节点应用程序(即 "type":"module"
在 package.json
中,并使用 import
和 export
整个过程),而无需转换为ES5.但是我想利用一些较早的库,例如使用CommonJS/ require
格式的express和socket.io.对于将CommonJS模块组合到ES6应用程序中,我有哪些选择(截至5/2020,节点12.16.3)?
I have a node app that I'd like to use in the standard ES6 module format (i.e., "type": "module"
in the package.json
, and using import
and export
throughout) without transpiling down to ES5. But I would like to take advantage of some older libraries such as a express and socket.io that use CommonJS / require
format. What are my options (as of 5/2020, Node 12.16.3) for combining CommonJS modules into an ES6 app?
推荐答案
使用CommonJS模块非常简单.您只能从CommonJS模块进行 default
导出.
Working with CommonJS modules is pretty straight forward.
You can only do default
exports from CommonJS modules.
import packageMain from 'commonjs-package'; // Works
import { method } from 'commonjs-package'; // Errors
这意味着所有commonjs导出都将驻留在 packageMain
对象上,并且您需要 dot 进入packageMain对象以提取所需的内容.
This means that all commonjs exports will live on the packageMain
object, and you need to dot in to the packageMain object to pickup what you need.
packageMain.method1()
这篇关于如何在ES6模块节点应用程序中包含commonjs模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!