本文介紹了在VSCode環(huán)境下如何配置eslint進(jìn)行代碼檢查师妙,并介紹了如何對(duì).vue單文件進(jìn)行支持。
ESLint 安裝
- 在工程根目錄下媒抠,安裝eslint及初始化
$ npm install eslint --save-dev
$ ./node_modules/.bin/eslint -- --init //會(huì)輸出幾個(gè)問題蝇完,指引配置eslint,我們選擇通用方案即可
1.? How would you like to configure ESLint? Use a popular style guide
2.? Which style guide do you want to follow? Standard
3.? What format do you want your config file to be in? JavaScript
2.通過以上步驟會(huì)在根目錄下生成.eslintrc.js文件
module.exports = {
"extends": "standard"
};
3.輸入以下命令嘗試對(duì).js文件進(jìn)行eslint檢測(cè)和修復(fù)
./node_modules/.bin/eslint -- --fix /path/to/file.js
4.安裝vscode插件 ESLint
該插件可以在編輯時(shí)自動(dòng)進(jìn)行eslint檢測(cè)和保存修復(fù)等功能樊卓,免除頻繁輸入命令行拿愧,提高效率
安裝完ESLint并重啟vscode后,可以在VSCode中打開一個(gè)js文件,檢查出錯(cuò)的地方就會(huì)有標(biāo)紅碌尔,且有eslint的提示浇辜。
- 設(shè)置保存時(shí)自動(dòng)修復(fù)
打開vscode -> 首選項(xiàng) ->設(shè)置
添加以下配置,即可實(shí)現(xiàn)保存時(shí)自動(dòng)修復(fù)唾戚。
"eslint.autoFixOnSave": true,
"eslint.validate":[
{
"language": "javascript",
"autoFix": true
}
"javascriptreact",
]
需要注意的是柳洋,在ESLint的文檔中有一段說明:
eslint.autoFixOnSave - enables auto fix on save. Please note auto fix on save is only available if VS Code's files.autoSave is either off, onFocusChange or onWindowChange. It will not work with afterDelay
即保存時(shí)自動(dòng)修復(fù)的功能只有在vscode的files.autoSave 配置不為afterDelay時(shí)才能生效,此項(xiàng)配置默認(rèn)為off
通過以上幾步叹坦,我們已經(jīng)實(shí)現(xiàn)了在VSCode中對(duì)js文件編輯時(shí)檢測(cè)熊镣,和保存自動(dòng)修復(fù)的功能。
對(duì)Vue單文件檢查
1.首先安裝VSCode的插件 Vetur
該插件可以對(duì)Vue的三個(gè)代碼塊分別高亮募书,且提供腳手架命令快速生成一段Vue單文件模板,結(jié)合eslint可對(duì)三大部分進(jìn)行代碼檢查
2.安裝eslint-html插件,及修改配置文件,未安裝時(shí)绪囱,無法正確識(shí)別vue文件中的<template></template>區(qū)域內(nèi)的html代碼
$ npm install eslint-plugin-html --save-dev
修改 eslintrc.js文件
module.exports = {
"extends": "standard",
"plugins":[
"html"
]
};
3.vscode -> 首選項(xiàng) ->設(shè)置
"files.associations": {
"*.vue": "vue"
},
"eslint.validate": [
"javascript",
"javascriptreact",
{
"language": "vue",
"autoFix": true
}
]
經(jīng)過以上幾步,不出意外就可以愉快地對(duì).vue文件進(jìn)行eslint檢查锐膜,并且通過保存自動(dòng)進(jìn)行修復(fù)毕箍。可以提高以后的編碼效率道盏。
額外的配置項(xiàng)
- 對(duì)es6的支持而柑,如 import()函數(shù)
.eslintrc.js 文件
module.exports = {
"extends": "standard",
"plugins":[
"html"
],
"parser": "babel-eslint",
"env": { "es6": true },
"rules": {
//"off" or 0 - turn the rule off
//"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
//"error" or 2 - turn the rule on as an error (exit code is 1 when triggered)
//require the use of === and !==
"eqeqeq" : 0,
"one-var": 0,
}
};
- vue單文件style語法配置
如果在style中使用了scss文捶,默認(rèn)情況下, eslint會(huì)提示出錯(cuò)媒咳,此時(shí)需要設(shè)置style的lang屬性粹排,更改后即可正常提示
<style scoped lang='scss'>
</style>
以上