【简易教程】基于Vue-cli使用eslint指南
【簡易教程】基于Vue-cli使用eslint指南
插件安裝
首先在vscode插件中搜索eslint和prettier。
啥也不管,這倆必須得裝。
插件簡介
vscode插件庫里的eslint是用來在你寫代碼的時候就直接給你報錯。(vue-cli中的eslint是在瀏覽器中報錯)
prettier是代碼格式化插件,用來輔助eslint,否則你調了花半天,一格式化全沒有。
實戰演練
# 創建一個vue項目 vue-cli@2.9.6,更高版本請使用create創建項目。 vue init webpack eslint_testeslint那一欄請選擇none,這樣vue-cli會幫你下載eslint,并進行一些基本的配置。
但是不會幫你設置rules(rules就是各種代碼規范的不允許)。
下載好后目錄結構如下:
文件介紹
里面有兩個文件非常重要。
.eslintignore 和 .eslintrc.js
.eslintignore ,見名知意,ignore 忽視一些文件。即在文件里面規定的不會被eslint進行檢查。
例如這里面不會對/build/文件下面的文件做語法檢查。
.eslintrc.js ,是eslint能起作用的根本。vue-cli里面eslint和vscode里的eslint都以這個文件為判定標準。
補充文件
我們得在根目錄下新建一個.prettierrc文件。
.prettierrc,是prettier格式化的配置文件,建議用json格式書寫。
例如你如果配置下面樣式。
{// 采用分號"semi": true,// 采用單引號"singleQuote": true,// tab采用兩個空格長度"tabWidth": 2 }格式化過程就會像下圖所示:
雙引號自動改成單引號,沒加的分號,自動補齊。
Eslint.js配置
上文中說過,.eslintrc.js是eslint起作用的關鍵文件,所以我們必須學會進行一些配置。
如果安裝eslint的時候選擇none,.eslintrc.js文件應該和下面是一樣的。
// https://eslint.org/docs/user-guide/configuringmodule.exports = {root: true,parserOptions: {parser: 'babel-eslint'},env: {browser: true,},// https://github.com/vuejs/eslint-plugin-vue#priority-a-essential-error-prevention// consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.extends: ['plugin:vue/essential'],// required to lint *.vue filesplugins: ['vue'],// add your custom rules hererules: {// allow debugger during development'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'} }上面最重要的模塊就是rules模塊。它是給我們來設定一些eslint的規則的。
例如我在rules里面添加一條規則’no-var’: [‘error’],此時我們就不能在程序中使用var來定義變量了。
只能使用let來定義變量,const來定義常量。
rules: {// allow debugger during development'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off','no-var': ['error'],},例如下圖中,我寫了var a = 1;它直接報錯了。
其他的也與之類似。附常用rule:
rules: {// allow debugger during development'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off','no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',// 尾隨逗號規則'comma-dangle': ['error',{arrays: 'always',objects: 'always',imports: 'never',exports: 'never',functions: 'never',},],// 禁止使用var規則'no-var': ['error'],// 必須使用分號semi: ['error', 'always'],// 必須使用單引號quotes: ['error', 'single'],// 必須使用兩個空格進行縮進indent: ['error', 2],},附錄官網
prettier官網 https://prettier.io/docs/en/configuration.html
eslint官網 https://eslint.bootcss.com/docs/rules/
airbnb中文文檔 https://github.com/BingKui/javascript-zh#functions
總結
以上是生活随笔為你收集整理的【简易教程】基于Vue-cli使用eslint指南的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【IDEA】自动导入无歧义的包
- 下一篇: vue-router常见问题解决方案。(