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

  • Node.js Web Development
  • David Herron
  • 277字
  • 2021-06-25 21:54:04

Supporting ES6 modules on older Node.js versions

While support for ES6 modules arrived as an experimental feature in Node.js 8.5, there are two ways to use these modules on earlier Node.js implementations. 

One method is to use the Babel transpiler to rewrite ES6 code so it can execute on older Node.js versions. For an example, see https://blog.revillweb.com/using-es2015-es6-modules-with-babel-6-3ffc0870095b.

The better method is the esm package in the Node.js registry. Simply do the following:

$ nvm install 6
Downloading and installing node v6.14.1...
Downloading https://nodejs.org/dist/v6.14.1/node-v6.14.1-darwin-x64.tar.xz...
######################################################################## 100.0%
Computing checksum with shasum -a 256
Checksums matched!
Now using node v6.14.1 (npm v3.10.10)
$ nvm use 6
Now using node v6.14.1 (npm v3.10.10)
$ npm install esm
... npm output
$ node
--require esm simpledemo.mjs
Hello, world!
1 1
2 4
2 4
3 9
4 16
5 25
42

To use this module, one simply invokes require('esm') once, and ES6 modules are retrofitted into Node.js.  The --require flag automatically loads the named module.  Without rewriting the code, we can selectively use the esm module with this the command-line option.  

This example demonstrates retrofitting ES6 modules into older Node.js releases.  To successfully execute the ls.mjs example   we must have support for async/await functions, and arrow functions.  Since Node.js 6.x does not support either, the ls.mjs example will fail, and will necessitate rewriting such code:

$ node --version
v6.14.1
$ node -r esm ls.mjs
/Users/David/chap03/ls.mjs:5
(async () => {
^

SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)

For more information, see: 
https://medium.com/web-on-the-edge/es-modules-in-node-today-32cff914e4b.  That article describes an older release of the esm module, at the time named @std/esm.

主站蜘蛛池模板: 如皋市| 恩平市| 垣曲县| 若尔盖县| 威海市| 彝良县| 盐池县| 明星| 西华县| 芜湖县| 龙南县| 岫岩| 西乌珠穆沁旗| 琼结县| 义马市| 个旧市| 潞城市| 阜城县| 鄂尔多斯市| 巨野县| 兰考县| 舟山市| 韶关市| 康马县| 四川省| 普兰县| 佛学| 萍乡市| 永兴县| 宁陵县| 云霄县| 饶河县| 海兴县| 玛曲县| 咸丰县| 满城县| 徐闻县| 蒙自县| 会理县| 濉溪县| 西藏|