- Node.js Web Development
- David Herron
- 258字
- 2021-06-25 21:54:05
Hybrid CommonJS/Node.js/ES6 module scenarios
We've gone over the format for CommonJS/Node.js modules, the format for ES6 modules, and the algorithm for locating and importing both. The last thing to cover is those hybrid situations where our code will use both module formats at the same time.
As a practical matter, ES6 modules are very new to the Node.js platform, and therefore we have a large body of existing code written as CommonJS/Node.js modules. Many tools in the Node.js market have implementation dependencies on the CommonJS format. This means we'll be facing situations where ES6 modules will need to use CommonJS modules, and vice versa:
- CommonJS module loads other CommonJS modules with require()
- CommonJS module cannot load ES6 modules—except for two methods:
- Dynamic import, also known as import(), can load an ES6 module as an asynchronous operation
- The @std/esm package supplies a require() function with one that can load ES6 modules as an asynchronous operation
- ES6 modules load other ES6 modules with import, with the full semantics of the import statement
- ES6 modules load CommonJS modules using import
Therefore, out of the box, three of the scenarios are directly supported. The fourth is supported with a workaround module.
When an ES6 module loads a CommonJS module, its module.exports object is exposed as the default export of the module. This means your code uses this pattern:
import cjsModule from 'common-js-module';
...
cjsModule.functionName();
This is extremely similar to using a CommonJS module in another CommonJS module. You are simply transliterating the require() call into an import statement.
- Flask Web全棧開發(fā)實戰(zhàn)
- Computer Vision for the Web
- Instant Zepto.js
- C/C++常用算法手冊(第3版)
- Elasticsearch for Hadoop
- H5頁面設(shè)計:Mugeda版(微課版)
- Hands-On Full Stack Development with Go
- PHP+MySQL+Dreamweaver動態(tài)網(wǎng)站開發(fā)從入門到精通(第3版)
- Yii Project Blueprints
- Visual Foxpro 9.0數(shù)據(jù)庫程序設(shè)計教程
- D3.js By Example
- Illustrator CC平面設(shè)計實戰(zhàn)從入門到精通(視頻自學(xué)全彩版)
- Instant Automapper
- Python Machine Learning Cookbook
- 你好!Java