How 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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.

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.

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.

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

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.

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.

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.

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.
