Javascript的项目与babel和eslint

最近开始弄hubot,顺带也开始学习 javascript ,首先从单独一个 nodejs 项目开始:

nvm 和 node 的安装使用在前面已经说过了: Nodejs多版本的安装与管理

新建一个项目目录,build01

然后在其下建立如下目录结构:

1mkdir build01
2
3cd build01
4mkdir es6 dist
5
6mkdir public
7cd public
8mkdir es6 dist 

image-20220104160358593

解释一下,es6 下放的是服务器端的源代码,dist 下放的是服务器端处理过的源代码。

public/es6 放的是浏览器端的源代码,public/dist 放的是浏览器端处理过的源代码。

一、安装gulp和babel

babel 是用来做 js 格式转换的,注意,原有的 babel-preset-es2015 已经不适用了。

1npm install --save-dev gulp gulp-babel babel-preset-env@next

生成一个.babelrc 文件,内容就一行

1{ "presets": ["env"] }

在 es6 目录下,建立一个测试的 test.js 文件,内容如下:

 1'use strict';
 2
 3const sentences = [
 4  { subject: 'JavaScript', verb: 'is',  object: 'great' },
 5  { subject: 'Elephants',  verb: 'are', object: 'large' },
 6];
 7
 8function say({ subject, verb, object }) {
 9  console.log(`${subject} ${verb} ${object}`);
10}
11
12for ( let s of sentences) {
13  say(s);
14}

仔细看,上面这个文件用到了 es6 的语法,对象的解构,of语法。

我们来用 babel 把它转换一下,变成 es5 的语法

在build01目录下,生成gulpfile.js,内容如下:

 1const gulp = require('gulp');
 2const babel = require('gulp-babel');
 3
 4
 5gulp.task('default', done =>{
 6
 7  gulp.src("es6/**/*.js")
 8  .pipe(babel())
 9  .pipe(gulp.dest("dist"));
10
11  gulp.src("public/es6/**/*.js")
12  .pipe(babel())
13  .pipe(gulp.dest("public/dist"));
14
15  done();
16   
17});

注意上面,**表示洞穿所有子目录。运行 gulp ,就会在 dist 目录下生成新的 test.js ,内容如下:

 1'use strict';
 2
 3var sentences = [{
 4  subject: 'JavaScript',
 5  verb: 'is',
 6  object: 'great'
 7}, {
 8  subject: 'Elephants',
 9  verb: 'are',
10  object: 'large'
11}];
12
13function say(_ref) {
14  var subject = _ref.subject,
15      verb = _ref.verb,
16      object = _ref.object;
17  console.log("".concat(subject, " ").concat(verb, " ").concat(object));
18}
19
20for (var _i = 0; _i < sentences.length; _i++) {
21  var s = sentences[_i];
22  say(s);
23}

仔细看,es6 的语法 变成 es5 的语法了。

二、安装eslint

babel 是对语法进行转换,那么 eslint 就是对语法作出规范,很多人吃 airbnb 那一套规则。

1npm install --save-dev eslint gulp-eslint gulp-if

安装完成后执行命令进行初始化:

1eslint --init

会提问一堆问题:

 1How would you like to use ESLint? … 
 2▸ To check syntax, find problems, and enforce code style
 3  
 4What type of modules does your project use? … 
 5▸ JavaScript modules (import/export)  
 6
 7Which framework does your project use? … 
 8  React
 9  Vue.js
10▸ None of these
11
12Does your project use TypeScript? ‣ No / Yes
13
14#两个都选哦
15Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
16✔ Browser
17✔ Node
18
19How would you like to define a style for your project? … 
20▸ Answer questions about your style
21
22✔ What format do you want your config file to be in? · JSON
23✔ What style of indentation do you use? · 4
24✔ What quotes do you use for strings? · single
25✔ What line endings do you use? · unix
26✔ Do you require semicolons? · Yes

最后得到文件 .eslintrc.json

 1{
 2    "env": {
 3        "browser": true,
 4        "es2021": true,
 5        "node": true
 6    },
 7    "extends": "eslint:recommended",
 8    "parserOptions": {
 9        "ecmaVersion": 13,
10        "sourceType": "module"
11    },
12    "rules": {
13        "indent": [
14            "error",
15            4
16        ],
17        "linebreak-style": [
18            "error",
19            "unix"
20        ],
21        "quotes": [
22            "error",
23            "single"
24        ],
25        "semi": [
26            "error",
27            "always"
28        ]
29    }
30}

这里注意,要改两个地方:

1"es2021": true,
2改成
3"es6": true,
4
5"ecmaVersion": 13,
6改成
7"ecmaVersion": 10,

然后我们改写一下 gulpfile.js,增加 eslint 的部分

 1const gulp = require('gulp');
 2const babel = require('gulp-babel');
 3const eslint = require('gulp-eslint');
 4const gulpIf = require('gulp-if');
 5
 6function isFixed(file) {
 7  return file.eslint !== null && file.eslint.fixed;
 8}
 9
10gulp.task('default', done =>{
11
12  gulp.src(["es6/**/*.js", "public/**/*.js"])
13  .pipe(eslint({fix: true}))
14  .pipe(eslint.format())
15  .pipe(gulpIf(isFixed, gulp.dest(file => file.base)))
16  .pipe(eslint.failAfterError());
17
18
19  gulp.src("es6/**/*.js")
20  .pipe(babel())
21  .pipe(gulp.dest("dist"));
22
23  gulp.src("public/es6/**/*.js")
24  .pipe(babel())
25  .pipe(gulp.dest("public/dist"));
26
27  done();
28   
29});

再运行 gulp ,会把 es6/test.js 给格式化好,对比一下原文件就知道了,ident 被调整成4个空格了:

 1'use strict';
 2
 3const sentences = [
 4    { subject: 'JavaScript', verb: 'is',  object: 'great' },
 5    { subject: 'Elephants',  verb: 'are', object: 'large' },
 6];
 7
 8function say({ subject, verb, object }) {
 9    console.log(`${subject} ${verb} ${object}`);
10}
11
12for ( let s of sentences) {
13    say(s);
14}

Hubot集成企业微信+jenkins+ansible
Grafana画出prometheus的图
comments powered by Disqus