校验工具(ESLint、Stylelint)

2022-01-17  本文已影响0人  JerrySi

一、ESLint基础

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

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

// 检查文件
eslint [文件路径] 

 // 自动修复
eslint [文件路径] --fix

二、ESLint配置文件

module.exports = {
  // 浏览器环境, 可以设置多个,如:node: true,
  env: {
    browser: false,
    es6: false
  },
  extends: [
    // 继承其他规则,/node-modules/eslint-config-standard包中
    'standard'
  ],
  // 只语法检查, 不检查es+新对象是否可用
  parserOptions: {
    ecmaVersion: 2015
  },
  rules: {
    // 0=off, 1=warn, 2=error
    // 使用数字或者字符串都可以
    'no-alert': "error"
  },
  globals: {
    // 全局注册一个jQuery只读变量
    "jQuery": "readonly"
  }
}

image.png

三、ESLint 配置注释

eslint-disable-line标识不处理
ESLint规则

// 添加eslint-disable-line标识不处理这行错误
// 添加no-template-curly-in-string 标识代表不处理这个指定的错误
const str1 = "${name} is a coder" // eslint-disable-line no-template-curly-in-string 

四、ESLint结合gulp

// gulp-eslint

// gulpfile.js
const script = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    // 对源代码检查
    .pipe(plugins.eslint())
    // 格式输出
    .pipe(plugins.eslint.format())
    // 发现问题立即停止
    .pipe(plugins.eslint.failAfterError())
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

四、ESLint结合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结合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

上一篇 下一篇

猜你喜欢

热点阅读