- 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.
- Progressive Web Apps with React
- C語言程序設(shè)計(jì)(第3版)
- Learning Docker
- 摩登創(chuàng)客:與智能手機(jī)和平板電腦共舞
- The Professional ScrumMaster’s Handbook
- HTML+CSS+JavaScript網(wǎng)頁設(shè)計(jì)從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Android應(yīng)用開發(fā)深入學(xué)習(xí)實(shí)錄
- Java Web開發(fā)實(shí)例大全(基礎(chǔ)卷) (軟件工程師開發(fā)大系)
- 零基礎(chǔ)C#學(xué)習(xí)筆記
- Drupal 8 Development:Beginner's Guide(Second Edition)
- After Effects CC技術(shù)大全
- Python 快速入門(第3版)
- RESTful Web API Design with Node.js
- Clojure Data Structures and Algorithms Cookbook
- Mastering R for Quantitative Finance