Home > Web Front-end > JS Tutorial > body text

How to use ES6 syntax in Node (detailed tutorial)

亚连
Release: 2018-06-13 16:08:58
Original
2350 people have browsed it

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
Copy after login

Basic knowledge

babel’s configuration file is .babelrc

{
 "presets": []
}
Copy after login
Copy after login

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

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

At the same time create a new .babelrc configuration file

{
 "presets": []
}
Copy after login
Copy after login

Run on the terminal

babel 1.js -o dist.js
Copy after login
Copy after login
Copy after login

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
Copy after login

Modify configuration file

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

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
Copy after login
Copy after login
Copy after login

You can see that the arrow function has been transcoded

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

Let’s try async await

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

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');
 });
}
Copy after login

Try import export

util.js

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

1.js

import say from './util';
say();
Copy after login

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

babel demo -d dist
Copy after login

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
Copy after login

.babelrc

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

1.js

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

After compilation

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

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
Copy after login
npm install koa --save
Copy after login

Create a new folder app

util.js

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

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);
Copy after login

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

node app
Copy after login
Copy after login

We need an entry file to transcode

index.js

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

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
Copy after login

This time, just start app.js under dist

node app
Copy after login
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!