Explain how to use ES6 elegantly in the NodeJS project, and explain how to use es6 in the nodejs Project

Source: Internet
Author: User
Tags npm scripts

Explain how to use ES6 elegantly in the NodeJS project, and explain how to use es6 in the nodejs Project

Node. js supports new features of ES6 (ES2015) In recent versions. The settings support more advanced features such as async and await. You only need to add the parameter -- harmony after the node when using it. However, even so, node still does not support all ES6 features. So we need to use Babel at this time.

Project address: https://github.com/future-challenger/petshop

Now start Babel

Before getting started with Babel, assume that

1. You have installed nodejs and are familiar with Js.

2. You can also use npm to install various dependency packages.

3. You are also familiar with ES6 (later changed to ES2015.

In addition, assume that you have installed yarn and are familiar with yarn. The biggest advantage of Yarn is that it is much faster than npm, because yarn only downloads the required database once and directly uses the locally cached version when used later. Npm downloads these libraries each time. This is a waste of life. If you have not installed yarn, it does not matter. The following describes how to use npm.

Next, install and configure Babel. Install babel-cli

yarn add babel-cli --dev  // npm install --save-dev babel-cli

Install babel presets.

yarn add babel-preset-es2015 --dev  // npm install --save-dev babel-preset-es2015

In this case, you can use ES2015 features. However, this is not enough, for example, I don't want to usePromiseI want to use more convenientasync/awaitSyntax. Only es2015 preset is not enough.

Babel plugin and preset

Babel itself does not process Transcoding of language features. These functions are implemented by plugin and preset (preset is also a set of plugin ). As described above, to use es2015 content, you need to install the babel-preset-es2015 preset. To use async/await, you need to install the corresponding preset or plug-in. To make it simple, install preset: babel-preset-stage-0. Preset stage-0 contains plug-ins related to async/await: babel-plugin-syntax-async-functions and babel-plugin-transform-regenerator.

Copy codeThe Code is as follows:
Yarn add babel-preset-stage-0 -- dev // npm install -- save-dev babel-preset-stage-0

In this way, the async/await of es7 cannot be used in the project. You also need more configurations. There are two ways to achieve this:

1. Usebabel-polyfill. There is a bad thing,babel-polyfillIt will pollute the global object, so it is not suitable for use in libraries and the like. Applicable only to web apps.

2. Use the transcoding tool for babel runtime,transform-runtimePlug-ins. This method makes up for the shortcomings of the above method. It is especially suitable for projects such as libraries.

These two methods are described respectively.

Installbabel-polyfill:

Copy codeThe Code is as follows:
Yarn add babel-polyfill -- dev // npm install -- save-dev babel-polyfill

Then, introducebabel-polyfill. For example, if I have an Express Web App, the entry file is to open the index. js file of the app. Introduce polyfill at the top of the file,require('babel-polyfill'). Or your entry file is already written in ES2015, so you can directly import it,import 'babel-polyfill'.

Usetransform-runtimeIt is also very simple. Installation:

Copy codeThe Code is as follows:
Yarn add babel-plugin-transform-runtime -- dev // npm install -- save-dev babel-plugin-transform-runtime

You also need to install babel-runtime:

yarn add babel-runtime // npm install --save babel-runtime

Then add the following configuration in the. babelrc file. Select either of the two:

// without options{ "plugins": ["transform-runtime"]}// with options{ "plugins": [  ["transform-runtime", {   "helpers": false, // defaults to true   "polyfill": false, // defaults to true   "regenerator": true, // defaults to true   "moduleName": "babel-runtime" // defaults to "babel-runtime"  }] ]}

The rest is the use of async/await.

If you want to useObject.assingIn this way, you can also use the plug-in:babel-plugin-transform-object-assignIf you want to use deconstruct value assignment, you can use the plug-in:babel-plugin-transform-object-rest-spread. Of course, these are included in the preset stage-0.

Now let's start writing ES2015 code. Install ExpressJs in the project and create an index. js file. Let's try to create a small web app as an exercise:

import Express from 'express'let app = Express()app.get('/', (req, res) => { res.send('hello world')})app.listen(8080, () => console.log('server is running at http://localhost:8080'))

Run the following command:

Copy codeThe Code is as follows:
./Node_modules/. bin/babel-node index. js -- preset es2015, stage-0

Run the ** babel-node ** command to run the code. The following parameters specify the preset and plugin used to escape JavaScript code.

The method officially recommended by Babel is to use the. babelrc file, which can be more flexible. Create the. babelrc file in the project directory and add the preset and plugin descriptions you have installed to it:

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

In this way, you can directly use babel-node to execute the code, or use the babel command to escape the code. For example:

babel -w code/ -d build/

The babel command reads the configuration from the configuration file, mutates the files in the code/directory, and exports the escaped JavaScript files to the build/directory. The-w parameter in the command line also specifies watch. Every time the code directory file is modified, the babel command is executed again.

Use Source Maps in files

The above looks pretty good. However, there is another problem. During code debugging, the debugging is actually the JavaScript code after the babel command is transcoded, not the file where the source code you originally compiled is located. Debugging is not a source file, which may cause some inconvenience. For example, the following file throws an exception:

async function errorAsyncFunc() { try{  throw new Error('Async function error') } catch(e) {  throw e }}errorAsyncFunc()

Add--source-mapsThis problem can be solved:

Babel code/-d build/-- source-maps

Finally, add the scripts node to package. json:

"scripts": { "build": "babel src -d build --source-maps", "start": "node build/index.js"},

Next:

npm run build

Gulp appearance

The previous section describes how to use Babel to develop ES201x. However, during the formal development, the above configurations are not enough. In particular, your project includes the web end and server end. In particular, the web end must not only process ES201x code, but also. Therefore, Gulp is required.

This seems complicated. You have defined the compilation process. In fact, it will be easy to use in the future, especially when many things can be automatically processed, saving a lot of time. To use Gulp, you must first install NodeJS. This is standard. Then you will use its command line tool.

Install Gulp

There is a slight adjustment in the latest release of Gulp. Gulp-cli is separated from gulp and used as a separate part. Therefore, if you have installed a version earlier than gulp, delete it first:

npm rm --global gulp

Install gulp-cli

yarn global add gulp-cli // npm install --global gulp-cli

Install gulp in -- dev Mode

yarn add gulp --dev   // npm install --save-dev gulp

Create a gulp configuration file

Just as Babel uses. babelrc as the configuration file, gulp also needs a configuration file. This configuration file is gulpfile. js, but with babel, we rename gulpfile. js to gulp. babel. js:

mv "gulpfile.js" "gulpfile.babel.js"

gulpIt is very easy to use, mainly to add various tasks in the gulpfile. babel. js file. In these tasks, you must add a task called default. The starting point for executing the gulp command is from here.

Suppose there is a scenario:

1. Use eslint to check the code and discover the code style and potential errors.

2. Automatically transcode ES201x-> ES5 and put the transcoded code under the specified directory.

3. Add sourcemaps during transcoding.

All the above "tasks" are automatically implemented using gulp. How can I configure it?

Gulp and eslint

To use a variety of features such as eslint in gulp, use the corresponding plug-in on gulp. Right, the design of gulp is basically the same as that of gulp: plug-in mechanism.

First, we need to download the eslint plug-in:

yarn add --dev gulp-eslint  // npm install --save-dev gulp-eslint

Make the final preparations before writing our first task. First, configure the. eslintrc file. Eslint checks the code style according to the rules defined in this file. We do not prepare a large number of configuration rules, which is time-consuming and does not take care of the coding styles that have been retained in many projects. Therefore, it is best to use a set of airbnb rules.

Install eslint

yarn add --dev eslint // npm install --save-dev eslint

Then you can run the command to initialize the Configuration:./node_modules/.bin/eslint --init. You can also ignore this command to directly create a. eslintrc file.

Install eslint's airbnb Extension

To use a set of airbnb rules, you need to install their eslint extension:

Copy codeThe Code is as follows:
Yarn add eslint-config-airbnb -- dev // npm install -- save-dev eslint-config-airbnb

After the command is executed, the system prompts that some dependencies are not installed, which areeslint-plugin-import@^2.2.0,eslint-plugin-import@^2.2.0,eslint-plugin-jsx-a11y@^3.0.2. Install These dependencies one by one.

. Eslintrc

{ "env": {  "es6": true }, "rules": {  "semi": "off",  "import/no-extraneous-dependencies": ["error", {   "devDependencies": true,    "optionalDependencies": false,    "peerDependencies": false  }]  ,"quotes": ["error", "single", {"allowTemplateLiterals": true}] }, "extends": "airbnb"}

envThe specified environment supports es6, and rules specifies supplementary content, such as single quotes or double quotation marks for strings. This is configured according to your preferences. You can add the rules you need. Finally, extends. Now we configure airbnb to use an eslint encoding check rule from airbnb.

Use the gulp-eslint plug-in

Import gulp from 'gulp' import eslint from 'Gulp-eslint // configure the file directory to be processed and the file storage directory after transcoding. const paramConfig = {source: 'src /**/*. js', dest: 'built ',}

After the relevant modules are introduced, write the task:

 

Gulp. task ('lint', () => {// configure eslint and use the configured file directory. Exclude all files under node_modules. Return gulp. src ([paramConfig. source ,'! Node_modules/** ']). pipe (eslint ()). pipe (eslint. result (result => {console. log ('eslint result: $ {result. filePath} '); console. log ('# Messages :$ {result. messages. length} '); console. log ('# Warnings :$ {result. warningCount} '); console. log ('# Errors: $ {result. errorCount }');})). pipe (eslint. format ()). pipe (eslint. failOnError ())})

As described above, the default task is required:

Gulp. task ('default', ['lint'], function () {// execute this method after the lint task is successfully executed });

Go to the project directory and run the gulp command. The following output is displayed:

$ gulp[21:43:01] Requiring external module babel-register[21:43:01] Using gulpfile ~/Documents/test-polyfill/gulpfile.babel.js[21:43:01] Starting 'lint'...[21:43:02] Starting 'babel-sourcemaps'...ESLint result: ~/Documents/test-polyfill/src/index.js# Messages: 0# Warnings: 0# Errors: 0ESLint result: ~/Documents/test-polyfill/src/test.js# Messages: 0# Warnings: 0# Errors: 0[21:43:02] Finished 'lint' after 605 ms[21:43:02] Finished 'babel-sourcemaps' after 653 ms[21:43:02] Starting 'default'...gulp default task![21:43:02] Finished 'default' after 98 μs

Gulp and babel

This time, both babel and sourcemaps are handled.

First install the plug-in:

Copy codeThe Code is as follows:
Yarn add -- dev gulp-babel // npm install -- save-dev gulp-babel

import gulp-babelPlugin:

import babel from 'gulp-babel'import sourcemaps from 'gulp-sourcemaps'

Add task:

gulp.task('babel-sourcemaps', () => { return gulp.src(paramConfig.source)   .pipe(sourcemaps.init())  .pipe(babel())  .pipe(sourcemaps.write('.'))  .pipe(gulp.dest(paramConfig.dest))})

Modify default task:

javascript gulp.task('default', ['lint', 'babel-sourcemaps'], () => { console.log('gulp default task!') })

If you do not want to use sourcemaps, you can write as follows:

javascript gulp.task('babel', () => { return gulp.src(paramConfig.source) .pipe(babel()) .pipe(gulp.dest(paramConfig.dest)) })

Place gulp in the npm Command System

babelWe have already configured and configured gulp. Each command input by gulp is basically executed manually. Now we should make this command semi-automated.

Modify the package. json file and addscriptsNode:

 "scripts": {  "build": "gulp",  "start": "node build/index.js" },

As a result, many commands can be executed in npm scripts like gulp. For example, you can enter the following command in the Command baggage to implement lint and babel transcoding:

npm run build

Start execution:

npm start

Summary

Using bebel allows you to use the latest JavaScript language features in advance, which makes code compilation more concise and efficient. The code generated after babel transcoding is also a very standard ES5 writing method, and is in strict mode. Therefore, when writing ES201x code, you do not need to add'use strict'; Id.

Using gulp can automatically handle a lot of small but time-consuming tasks.

Combining these two methods will greatly improve your project development efficiency. So here, you don't think you should use these technologies in the project to bring development into the fast lane !!!???

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.