官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 长春市| 通州区| 宁津县| 明星| 新绛县| 松溪县| 盐山县| 巍山| 普兰县| 隆安县| 泰来县| 沙田区| 积石山| 望谟县| 乐业县| 巩义市| 东港市| 赞皇县| 兴山县| 普洱| 乐平市| 泾源县| 莱州市| 镇康县| 莲花县| 镇坪县| 潜江市| 明星| 增城市| 桓仁| 宁都县| 黔南| 石棉县| 双城市| 龙口市| 资中县| 平安县| 津南区| 冀州市| 府谷县| 青海省|