search
HomeWeb Front-endJS TutorialHow to use ES6 syntax in Node (detailed tutorial)

With the support of es6 by Google, firfox and node6.0, the finalization of es6 syntax has attracted more and more attention, especially since react projects are basically written in es6. The following article mainly introduces you to the basic tutorial on using ES6 syntax in Node. Friends who need it can refer to it.

Related background introduction

The syntax javascript that most of us use now is actually ecmscript5, which is also es5. This version has been available for many years and is perfectly supported by all major browsers. Therefore, many friends who learn js can never tell the relationship between es5 and javscript. JavaScript is a programming language, so it has a version. Whether es5 or es6 is its version number. The latest version of es7 is already in full swing, and its latest syntax will allow us to write code updates smoothly.

Introduction

Node itself already supports some ES6 syntax, but some syntax such as import export, async await (Node 8 already supports), We still can't use it. In order to use these new features, we need to use babel to convert ES6 to ES5 syntax

Install babel

npm install babel-cli -g

Basic knowledge

babel’s configuration file is .babelrc

{
 "presets": []
}

Create a demo folder , create a new 1.js in the folder

const arr = [1, 2, 3];
arr.map(item => item + 1);

At the same time create a new .babelrc configuration file

{
 "presets": []
}

Run on the terminal

babel 1.js -o dist.js

You can see that a new dist is created in the folder. js, this is the file transcoded by Babel

However, there is currently no change in dist.js, because we did not declare the transcoding rules in the configuration file, so Babel cannot transcode

Install transcoding plug-in

npm install --save-dev babel-preset-es2015 babel-preset-stage-0

Modify configuration file

{
 "presets": [
 "es2015",
 "stage-0"
 ]
}

es2015 can transcode es2015 grammar rules, stage-0 can transcode ES7 grammar (such as async await)

Run the terminal again

babel 1.js -o dist.js

You can see that the arrow function has been transcoded

var arr = [1, 2, 3];
arr.map(function (item) {
 return item + 1;
});

Let’s try async await

async function start() {
 const data = await test();
 console.log(data);
}
function test() {
 return new Promise((resolve, reject) => {
 resolve('ok');
 })
}

The transcoded file

'use strict';
var start = function () {
 var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
 var data;
 return regeneratorRuntime.wrap(function _callee$(_context) {
  while (1) {
  switch (_context.prev = _context.next) {
   case 0:
   _context.next = 2;
   return test();

   case 2:
   data = _context.sent;

   console.log(data);

   case 4:
   case 'end':
   return _context.stop();
  }
  }
 }, _callee, this);
 }));
 return function start() {
 return _ref.apply(this, arguments);
 };
}();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

function test() {
 return new Promise(function (resolve, reject) {
 resolve('ok');
 });
}

Try import export

util.js

export default function say() {
 console.log('2333');
}

1.js

import say from './util';
say();

again. This time, to transcode both 1.js and util.js, we can Transcoding the entire folder

babel demo -d dist

Under the newly generated dist folder, there are transcoded files. You can see that after transcoding, the module.exportsCMD module is still used to load

babel-preset-env

The transcoding above actually has a flaw, which is babel All codes will be converted to es5 by default, which means that even if node supports the let keyword, after transcoding, it will be converted into var

. We can use the babel-preset-env plug-in, which will Automatically detect the current node version and only transcode the syntax that node does not support, which is very convenient

npm install --save-dev babel-preset-env

.babelrc

{
 "presets": [
  ["env", {
  "targets": {
   "node": "current"
  }
  }]
 ]
 }

1.js

class F {
 say() {
  
 }
}
const a = 1;
babel 1.js -o dist.js

After compilation

"use strict";
class F {
 say() {}
}
const a = 1;

As you can see, class and const have not been transcoded because the current node version (8.9.3) supports this syntax

Use ES6 syntax in actual projects

Koa2 requires Node v7.6.0 or above to support async syntax. At the same time, we also want to use the import modular writing method in Koa2

npm install --save-dev babel-register
npm install koa --save

Create a new folder app

util.js

export function getMessage() {
 return new Promise((resolve, reject) => {
  resolve('Hello World!');
 })
}

app.js

import Koa from 'koa';
import { getMessage } from './util'
const app = new Koa();
app.use(async ctx => {
 const data = await getMessage();
 ctx.body = data;
});
app.listen(3000);

If you start the file directly, an error will definitely be reported

node app

We need an entry file to transcode

index.js

require("babel-register");
require("./app.js");
node index

Visit http://localhost:3000/ and you can see the page!

babel-register is transcoded in real time, so when actually publishing, the entire app folder should be transcoded first

babel app -d dist

This time, just start app.js under dist

node app

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to delete an element in a JS array

Introduces in detail the knowledge points about promises in js

How to solve the niceScroll scroll bar misalignment problem in jQuery

How to implement the Baidu search interface in JS

The above is the detailed content of How to use ES6 syntax in Node (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vercel是什么?怎么部署Node服务?Vercel是什么?怎么部署Node服务?May 07, 2022 pm 09:34 PM

Vercel是什么?本篇文章带大家了解一下Vercel,并介绍一下在Vercel中部署 Node 服务的方法,希望对大家有所帮助!

node.js gm是什么node.js gm是什么Jul 12, 2022 pm 06:28 PM

gm是基于node.js的图片处理插件,它封装了图片处理工具GraphicsMagick(GM)和ImageMagick(IM),可使用spawn的方式调用。gm插件不是node默认安装的,需执行“npm install gm -S”进行安装才可使用。

火了!新的JavaScript运行时:Bun,性能完爆Node火了!新的JavaScript运行时:Bun,性能完爆NodeJul 15, 2022 pm 02:03 PM

今天跟大家介绍一个最新开源的 javaScript 运行时:Bun.js。比 Node.js 快三倍,新 JavaScript 运行时 Bun 火了!

nodejs中lts是什么意思nodejs中lts是什么意思Jun 29, 2022 pm 03:30 PM

在nodejs中,lts是长期支持的意思,是“Long Time Support”的缩写;Node有奇数版本和偶数版本两条发布流程线,当一个奇数版本发布后,最近的一个偶数版本会立即进入LTS维护计划,一直持续18个月,在之后会有12个月的延长维护期,lts期间可以支持“bug fix”变更。

聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

node爬取数据实例:聊聊怎么抓取小说章节node爬取数据实例:聊聊怎么抓取小说章节May 02, 2022 am 10:00 AM

node怎么爬取数据?下面本篇文章给大家分享一个node爬虫实例,聊聊利用node抓取小说章节的方法,希望对大家有所帮助!

深入浅析Nodejs中的net模块深入浅析Nodejs中的net模块Apr 11, 2022 pm 08:40 PM

本篇文章带大家带大家了解一下Nodejs中的net模块,希望对大家有所帮助!

怎么获取Node性能监控指标?获取方法分享怎么获取Node性能监控指标?获取方法分享Apr 19, 2022 pm 09:25 PM

怎么获取Node性能监控指标?本篇文章来和大家聊聊Node性能监控指标获取方法,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version