首頁  >  文章  >  web前端  >  EsLint新手入門須知

EsLint新手入門須知

php中世界最好的语言
php中世界最好的语言原創
2018-05-24 14:05:323770瀏覽

這次帶給大家EsLint新手入門須知,EsLint新手入門須知的注意事項有哪些,下面就是實戰案例,一起來看一下。

介紹

  ESLint 是一個插件化的javascript 程式碼偵測工具,它可以用來檢查常見的JavaScript 程式碼錯誤,也可以進行程式碼風格檢查,這樣我們就可以根據自己的喜好指定一套ESLint 配置,然後應用到所編寫的項目上,從而實現輔助編碼規範的執行,有效控制專案代碼的品質。

安裝

ESLint的安裝:本機安裝、全域安裝

1、本機安裝

$ npm install eslint --save-dev

產生設定檔

$ ./node_modules/.bin/eslint --init

之後,您可以運行ESLint在任何檔案或目錄如下:

$ ./node_modules/.bin/eslint index.js

#index.js是你需要測試的js檔案。你使用的任何插件或共享配置(必須安裝在本地來與安裝在本地的ESLint一起工作)。

2、全域安裝

如果你想讓ESLint可用到所有的專案,建議全域安裝ESLint。

$ npm install -g eslint

產生設定檔

$ eslint --init

之後,您可以在任何檔案或目錄執行ESLint

$ eslint index.js

PS:eslint --init是用於每個項目設定和配置eslint,並將執行本地安裝的ESLint及其插件的目錄。如果你喜歡使用全域安裝的ESLint,在你設定中使用的任何插件都必須是全域安裝的。

使用

1、在專案根目錄產生package.json檔案(設定ESLint的專案中必須有package.json 文件,如果沒有的話可以使用npm init -y來產生

$ npm init -y

2、安裝eslint(安裝方式依個人專案需要安裝,這裡使用全域安裝

$ npm install -g eslint

3、建立index .js文件,裡面寫一個函數。

function merge () {
    var ret = {};
    for (var i in arguments) {
        var m = arguments[i];
        for (var j in m) ret[j] = m[j];
    }
    return ret;
}

console.log(merge({a: 123}, {b: 456}));

執行node index.js,輸出結果為{ a: 123, b: 456 }

$ node index.js
{ a: 123, b: 456 }

使用eslint檢查

$ eslint index.js
Oops! Something went wrong! :(

ESLint: 4.19.1.
ESLint couldn't find a configuration file. To set up a configuration file for this project, please run:

    eslint --init

ESLint looked for configuration files in E:\website\demo5\js and its ancestors. If it found none, it then looked in your home directory.

If you think you already have a configuration file or if you need more help, please stop by the ESLint chat room: https://gitter.im/eslint/eslint

執行結果是失敗,因為沒有找到相應的配置文件,個人認為這個eslint最重要的就是配置問題。

新設定​​檔

  $ eslint --init

產生的過程中,需要選擇產生規則、支援環境等內容,以下說明一些本人的生成選項

? How would you like to configure ESLint? Answer questions about your style
? Are you using ECMAScript 6 features? Yes
? Are you using ES6 modules? Yes
? Where will your code run? Browser
? Do you use CommonJS? Yes
? Do you use JSX? No
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Single
? What line endings do you use? Windows
? Do you require semicolons? No
? What format do you want your config file to be in? JavaScript

產生的內容在. eslintrc.js檔案中,檔案內容如下

module.exports = {
    "env": {
        "browser": true,
        "commonjs": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "sourceType": "module"
    },
    "rules": {
        "indent": [
            "error",
            "tab"
        ],
        "linebreak-style": [
            "error",
            "windows"
        ],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "never"
        ]
    }
};

  不過這個產生的額檔案裡面已經有一些設定了,把裡面的內容大部分刪除。留下個extends,剩下的自己填就可以了

 module.exports = {
      "extends": "eslint:recommended"
  };

eslint:recommended配置,它包含了一系列核心規則,能報告一些常見的問題。

重新執行eslint index.js,輸出如下

  10:1  error  Unexpected console statement  no-console
  10:1  error  'console' is not defined      no-undef

✖ 2 problems (2 errors, 0 warnings)

Unexpected console statement no-console --- 不能使用console
'console' is not defined     no-undef   --- console變數未定義,不能使用未定義的變數
一條一條解決,不能使用console的提示,那我們就禁用no-console就好了,在設定檔中加入rules

module.exports = {
    extends: 'eslint:recommended',
    rules: {
        'no-console': 'off',
    },
};

  設定規則寫在rules物件裡面,key表示規則名稱,value表示規則的配置。
  接著就是解決no-undef:出錯的原因是因為JavaScript有很多種運行環境,例如常見的有瀏覽器和Node.js,另外還有很多軟體系統使用JavaScript作為其腳本引擎,例如PostgreSQL就支援使用JavaScript來寫儲存引擎,而這些運行環境可能不存在console這個物件。另外在瀏覽器環境下會有window對象,而Node.js下沒有;在Node.js下會有process對象,而瀏覽器環境下沒有。
所以在設定檔中我們還需要指定程式的目標環境:

module.exports = {
    extends: 'eslint:recommended',
    env: {
        node: true,
    },
    rules: {
        'no-console': 'off',
    }
};

再重新執行檢查時,就沒有任何提示輸出了,表示index.js已經完全通過了檢查。

配置

配置方式有兩種:檔案配置方式、程式碼註解配置方式(建議使用檔案配置的形式,比較獨立,方便維護)。
使用檔案設定的方式:在專案的根目錄下,新建一個名為 .eslintrc 的文件,在此文件中新增一些檢查規則。

檔案設定方式

env:​​你的腳本將要執行在什麼環境中
Environment可以預設好的其他環境的全域變量,如brower、node環境變數、es6環境變數、mocha環境變數等

'env': {
    'browser': true,
    'commonjs': true,
    'es6': true
},

globals:額外的全域變數

globals: {
    vue: true,
    wx: true
},

rules:開啟規則和發生錯誤時報告的等級
規則的錯誤等級有三種:

0或’off’:关闭规则。 
1或’warn’:打开规则,并且作为一个警告(并不会导致检查不通过)。 
2或’error’:打开规则,并且作为一个错误 (退出码为1,检查不通过)。

参数说明: 
参数1 : 错误等级 
参数2 : 处理方式

設定程式碼註解方式

使用JavaScript 註解把設定資訊直接嵌入到一個檔案
範例:

忽略 no-undef 检查 
/* eslint-disable no-undef */

忽略 no-new 检查 
/* eslint-disable no-new */

设置检查 
/*eslint eqeqeq: off*/ 
/*eslint eqeqeq: 0*/

設定和規則的內容有不少,有興趣的同學可以參考這裡:rules

使用共享的配置文件

  我们使用配置js文件是以extends: 'eslint:recommended'为基础配置,但是大多数时候我们需要制定很多规则,在一个文件中写入会变得很臃肿,管理起来会很麻烦。

  新建一个文件比如eslint-config-public.js,在文件内容添加一两个规则。

module.exports = {
    extends: 'eslint:recommended',
    env: {
        node: true,
    },
    rules: {
        'no-console': 'off',
        'indent': [ 'error', 4 ],
        'quotes': [ 'error', 'single' ],
    },
};

然后原来的.eslintrc.js文件内容稍微变化下,删掉所有的配置,留下一个extends。

module.exports = {
    extends: './eslint-config-public.js',
};

  这个要测试的是啥呢,就是看看限定缩进是4个空格和使用单引号的字符串等,然后测试下,运行eslint index.js,得到的结果是没有问题的,但是如果在index.js中的var ret = {};前面加个空格啥的,结果就立马不一样了。

2:1  error  Expected indentation of 4 spaces but found 5  indent

✖ 1 problem (1 error, 0 warnings)
  1 error, 0 warnings potentially fixable with the `--fix` option.

  这时候提示第2行的是缩进应该是4个空格,而文件的第2行却发现了5个空格,说明公共配置文件eslint-config-public.js已经生效了。

  除了这些基本的配置以外,在npm上有很多已经发布的ESLint配置,也可以通过安装使用。配置名字一般都是eslint-config-为前缀,一般我们用的eslint是全局安装的,那用的eslint-config-模块也必须是全局安装,不然没法载入。

在执行eslint检查的时候,我们会经常看到提示“--flx”选项,在执行eslint检查的时候添加该选项会自动修复部分报错部分(注意这里只是部分,并不是全部

比如我们在规则中添加一条no-extra-semi: 禁止不必要的分号。

'no-extra-semi':'error'

然后,我们在index.js最后多添加一个分号

function merge () {
    var ret = {};
    for (var i in arguments) {
        var m = arguments[i];
        for (var j in m) ret[j] = m[j];
    }
    return ret;;
}

console.log(merge({a: 123}, {b: 456}));

执行eslint index.js,得到结果如下:

  7:16  error  Unnecessary semicolon  no-extra-semi
  7:16  error  Unreachable code       no-unreachable

✖ 2 problems (2 errors, 0 warnings)
  1 error, 0 warnings potentially fixable with the `--fix` option.

然后我们在执行eslint index.js --fix就会自动修复,index.js那个多余的分号也就被修复消失不见了。

总结

以上是我在学习eslint整理的一些资料,不算太全面,对于像我这样的新手入门足够了


相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

前端中排序算法实例详解

PromiseA+的实现步骤详解


以上是EsLint新手入門須知的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn