Home > Web Front-end > JS Tutorial > How to use ES6 in NodeJS projects

How to use ES6 in NodeJS projects

不言
Release: 2018-06-30 10:47:51
Original
2100 people have browsed it

This article mainly introduces in detail how to use ES6 elegantly in NodeJS projects. It has certain reference value. Interested friends can refer to it.

The latest versions of NodeJs have begun to support the new features of ES6 (ES2015), and the settings already support more advanced features such as async/await. Just when using it, you need to add the parameter after node: --harmony. However, even so node still does not support all ES6 features. So you need to use Babel at this time.

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

Start Babel now

Before starting to use Babel, assume

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

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

3. And you are also familiar with ES6 (later changed to ES2015) to a certain extent.

At the same time, it is assumed 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 libraries once, and directly uses the locally cached version when used later. npm will download these libraries every time. What a waste of life. If you haven't installed yarn yet, it doesn't matter. There are also instructions for using npm below.

Next, start installing and configuring Babel. Install babel-cli

yarn add babel-cli --dev  // npm install --save-dev babel-cli
Copy after login

Install babel’s presets.

yarn add babel-preset-es2015 --dev  // npm install --save-dev babel-preset-es2015
Copy after login

At this time you can use the features of ES2015. However, this is not enough. For example, I don’t want to use Promise. I want to use the more convenient async/await syntax. Only the es2015 preset is not enough.

Babel’s plugin and preset

Babel itself does not handle the transcoding of language features. These functions are implemented by plugin and preset (preset is also a collection of plugins). As mentioned 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. For simplicity we install preset: babel-preset-stage-0. preset stage-0 includes async/await related plug-ins: babel-plugin-syntax-async-functions, babel-plugin-transform-regenerator.

yarn add babel-preset-stage-0 --dev // npm install --save-dev babel-preset-stage-0
Copy after login

This way you still can’t use es7’s async/await in your project. More configuration is required. There are two ways to achieve the goal:

1. Use babel-polyfill. There is a disadvantage, babel-polyfill will pollute the global object, so it is not suitable for use in libraries and the like. Only suitable for web app use.

2. Use babel runtime transcoding tool, transform-runtime plug-in. Using this method just makes up for the shortcomings of the above method. It is especially suitable for projects such as libraries.

Introduce these two methods respectively.

After installing babel-polyfill:

yarn add babel-polyfill --dev // npm install --save-dev babel-polyfill
Copy after login

, introduce babel-polyfill# at the top of the entry file of your project ##. For example, I currently have an Express Web App, and the entry file is the index.js file that opens the app. Introduce polyfill at the top of this file, require('babel-polyfill'). Or your entry file is already written in ES2015, then import directly, import 'babel-polyfill'.

Using

transform-runtime is also very simple. Installation:

yarn add babel-plugin-transform-runtime --dev // npm install --save-dev babel-plugin-transform-runtime
Copy after login

You also need to install babel-runtime:


yarn add babel-runtime // npm install --save babel-runtime
Copy after login

and then add the following configuration to the .babelrc file, Just choose one 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"
  }]
 ]
}
Copy after login

The rest is to use async/await happily.

In addition, if you want to use a method like

Object.assing, you can also use the plug-in: babel-plugin-transform-object-assign, if you want to use destructuring assignment You can use the plug-in: babel-plugin-transform-object-rest-spread. Of course, these are included in the stage-0 preset.

Start writing ES2015 code now. Install ExpressJs in the project and create an index.js file. Let’s try creating 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'))
Copy after login

Run the command:

./node_modules/.bin/babel-node index.js --preset es2015, stage-0
Copy after login

Use the command *babel-node* * allows the code to run. The following parameters specify the preset and plugin used when escaping js code.

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

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

This way you can use babel-node directly. Execute the code, or use the command babel to escape the code. For example:

babel -w code/ -d build/
Copy after login

babel command will read the configuration from the configuration file, mutate the files in the code/ directory, and export the escaped JavaScript files Go to the build/ directory. There is also the parameter -w in the command line. This command parameter specifies watch. Every time the file in the code directory is modified, it will trigger the babel command to be executed again.

Using Source Maps in Files

上面看起来很不错了。但是还有一个问题,在你调试代码的时候,你调试的实际是babel命令转码之后的js,不是原来你编写的源代码所在的文件。调试的不是源文件,多少会有些不便。比如下面的文件会抛出一个异常:

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

errorAsyncFunc()
Copy after login

在转码命令中加一个--source-maps可以解决这个问题:

babel code/ -d build/ --source-maps

最后在package.json里添加scripts节点:

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

接下来:

npm run build
Copy after login
Copy after login

Gulp出场

上文讲述了如何使用Babel实现ES201x的开发。但是在正式的开发中,上面的这些配置还略显不足,尤其是你的项目包括web端、server端,尤其web端不仅处理ES201x的代码还需要处理。所以需要Gulp出场。

这玩意儿看起来很复杂,你定义了编译的过程。其实掌握了以后很好用,尤其是可以自动处理很多东西,节约大把时间。要使用Gulp,必须先安装NodeJS。这个基本是标配。然后你会用到它的命令行工具。

安装Gulp

在最新发布的Gulp里有一点调整。gulp-cli从gulp分离出来作为单独的一部分使用。所以,如果你已经安装过gulp之前的版本需要先删除:

npm rm --global gulp
Copy after login

安装gulp-cli

yarn global add gulp-cli // npm install --global gulp-cli
Copy after login

在--dev模式下安装gulp

yarn add gulp --dev   // npm install --save-dev gulp
Copy after login

创建gulp配置文件

就像Babel要用.babelrc作为配置文件一样,gulp也需要一个配置文件。这个配置文件就是gulpfile.js, 但是和babel同用的情况下把gulpfile.js重命名为gulp.babel.js:

mv "gulpfile.js" "gulpfile.babel.js"
Copy after login

gulp的使用还是很简单的,主要就是在gulpfile.babel.js文件中添加各种task。在这些task中一定要添加一个叫做default的task,gulp命令的执行起点就是从这里开始。

假设有这么一个场景:

1.使用eslint检查代码,发现代码风格和潜在的错误。

2.自动实现ES201x -> ES5的代码转码,并把转码后的代码放在指定目录下。

3.在转码的时候添加sourcemaps。

以上这些“任务”都是用gulp自动实现。该如何配置呢?

gulp和eslint

要在gulp中使用各种请他的类似于eslint这样的功能的时候需要使用在gulp上的对应的插件。没错,gulp的设计思路和gulp基本一样:插件机制。

那么我们就需要首先下载eslint的插件:

yarn add --dev gulp-eslint  // npm install --save-dev gulp-eslint
Copy after login

在开始编写我们的第一个task之前, 做最后的准备工作。首先需要配置.eslintrc文件。eslint会根据这个文件定义的规则检查代码的风格。我们不准备大批的配置规则,这样非常耗时间而且也照顾不到很多我们项目已经保留下来的编码风格。所以,airbnb的一套规则拿来使用时最好的办法。

安装eslint

yarn add --dev eslint // npm install --save-dev eslint
Copy after login

然后你可以运行命令来初始化配置:./node_modules/.bin/eslint --init。你也可以忽略这个命令,直接创建一个.eslintrc的文件。

安装eslint的airbnb扩展

要使用airbnb的一套规则就需要安装他们的eslint扩展:

yarn add eslint-config-airbnb --dev  // npm install --save-dev eslint-config-airbnb
Copy after login

命令执行之后会提示有些依赖项没有安装,分别是eslint-plugin-import@^2.2.0eslint-plugin-import@^2.2.0eslint-plugin-jsx-a11y@^3.0.2。依次安装这些依赖项就好。

.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"
}
Copy after login

env指定环境是支持es6的,rules指定的是一些补充内容,比如字符串使用单引号还是双引号等。这个是根据个人喜好配置的,你可以选择添加你需要的规则。最后是extends,这里配置airbnb就用上了airbnb的一套eslint编码检查规则。

gulp-eslint插件用起来

import gulp from 'gulp'
import eslint from 'gulp-eslint

// 配置需要处理的文件目录和转码之后文件的存放目录
const paramConfig = {
 source: 'src/**/*.js',
 dest: 'build',
}
Copy after login

引入相关模块之后开始写任务:

gulp.task('lint', () => {
 // eslint配置,使用配置的文件目录。排除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())
})
Copy after login

如前文所述,default任务是必须:

gulp.task('default', ['lint'], function () {
  // lint任务成功执行之后执行这个方法
});
Copy after login

跳转到项目的目录下,运行gulp命令。会得到如下的输出:

$ 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: 0
ESLint 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
Copy after login

gulp和babel

这次同时处理babel和sourcemaps的问题。

首先安装插件:

yarn add --dev gulp-babel   // npm install --save-dev gulp-babel
Copy after login

import gulp-babel插件:

import babel from 'gulp-babel'
import sourcemaps from 'gulp-sourcemaps'
Copy after login

添加任务:

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

修改default任务:

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

如果你不想用sourcemaps的话,可以这么写:

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

把gulp放在npm命令体系下

babel老早就配置好了,现在和配置好了gulp。gulp每次输入命令基本上就是手动执行。现在应该让这个命令半自动执行了。

修改package.json文件,在其中添加scripts节点:

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

如此一来,很多的命令都可以像gulp一样放在npm的scripts里执行。比如,现在可以在命令行李输入如下命令来实现lint和babel转码:

npm run build
Copy after login
Copy after login

开始执行:

npm start
Copy after login

总结

使用bebel可以提前使用最新的JavaScript语言特性,这样编写很多代码的时候会变得简洁高效。并且babel转码之后生成的代码也是非常规范的ES5写法,同时是在严格模式下的。所以,我们在写ES201x代码的时候不需要再添加'use strict';标识。

使用gulp又可以使很多不大不小但是很费时间的事自动处理。

把这两者结合在一起会让你的项目开发效率提升很多。所以,看到这里你不觉得你应该赶快在项目里使用这些技术,让开发进入快车道吗!!!???

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

关于NodeJS框架Express的模板视图机制分析

关于nodejs socket服务端和客户端的简单通信功能

The above is the detailed content of How to use ES6 in NodeJS projects. 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