Home Web Front-end JS Tutorial How to use ES6 syntax in Node (detailed tutorial)

How to use ES6 syntax in Node (detailed tutorial)

Jun 13, 2018 pm 04:08 PM
nodejs

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!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Which one to choose between nodejs and java? Which one to choose between nodejs and java? Apr 21, 2024 am 04:40 AM

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.

See all articles