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
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

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

Video Face Swap

Video Face Swap

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment