校驗工具(ESLint、Stylelint)

一、ESLint基礎

// 安裝
yarn add eslint --dev
eslint --version

// 初始化一個配置.eslintrc.js
eslint --init 

// 檢查文件
eslint [文件路徑] 

 // 自動修復
eslint [文件路徑] --fix

二、ESLint配置文件

module.exports = {
  // 瀏覽器環(huán)境, 可以設置多個,如:node: true,
  env: {
    browser: false,
    es6: false
  },
  extends: [
    // 繼承其他規(guī)則,/node-modules/eslint-config-standard包中
    'standard'
  ],
  // 只語法檢查, 不檢查es+新對象是否可用
  parserOptions: {
    ecmaVersion: 2015
  },
  rules: {
    // 0=off, 1=warn, 2=error
    // 使用數(shù)字或者字符串都可以
    'no-alert': "error"
  },
  globals: {
    // 全局注冊一個jQuery只讀變量
    "jQuery": "readonly"
  }
}

image.png

三、ESLint 配置注釋

eslint-disable-line標識不處理
ESLint規(guī)則

// 添加eslint-disable-line標識不處理這行錯誤
// 添加no-template-curly-in-string 標識代表不處理這個指定的錯誤
const str1 = "${name} is a coder" // eslint-disable-line no-template-curly-in-string 

四、ESLint結(jié)合gulp

// gulp-eslint

// gulpfile.js
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    // 對源代碼檢查
    .pipe(plugins.eslint())
    // 格式輸出
    .pipe(plugins.eslint.format())
    // 發(fā)現(xiàn)問題立即停止
    .pipe(plugins.eslint.failAfterError())
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

四、ESLint結(jié)合webpack

針對React沒有使用的報錯, 需要使用eslint-plugin-react
error 'React' is defined but never used

  // 1
  rules: {
    // 2代表error
    // 避免定義了React,但是沒有使用的報錯
    "react/jsx-uses-react": 2,
    "react/jsx-uses-vars": 2
  },
   plugins: [
     // eslint-plugin-react
     'react'
   ]

// 2
  extends: [
    'standard',
    // 共享配置
    // eslint-plugin-react提交了2個共享配置,all 和 recommended
    'plugin:react/recommended'
  ],

五、ESLint結(jié)合ts

需要配置語法解析器
parser: '@typescript-eslint/parser'

六、Stylelint-校驗CSS的工具

// 命令
yarn stylelint [文件名]

// .stylelintrc.js
module.exports = {
  extends: [
    // 共享配置, 需要完整的名字
    "stylelint-config-standard",
    // sass代碼
    "stylelint-config-sass-guidelines"
  ]
}

七、prettier-校驗所有文件工具

// 默認會把校驗后的信息打印在控制臺,需要使用write進行文件寫入
prettier [文件名] --write
 // . 代表所有文件
prettier . --write

八、git hooks

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容