美文网首页
安装eslint和prettier

安装eslint和prettier

作者: ghost_of_code | 来源:发表于2022-03-06 14:35 被阅读0次

    eslint

    1. 安装
    yarn add eslint -D
    
    2. 初始化
    ./node_modules/.bin/eslint --init
    
    3. vscode安装eslint插件,setting.json添加如下配置,保存时可自动修复;webstorm自带,打开自动eslint即可
    // setting.json
    "editor.formatOnType": true,
    "editor.formatOnSave": true,
    "eslint.codeAction.showDocumentation": {
      "enable": true
    },
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true,
    },
    "eslint.validate": ["javascript", "javascriptreact", "html", "vue"],
    
    4. package.json中添加指令,yarn lint:check检查文件,yarn lint:fix可以自动修复部分代码
    "scripts": {
      "lint:check": "eslint src",
      "lint:fix": "eslint --fix src"
    }
    
    5. 规则(不定时更新),0: 忽略,1: 警告,2: 报错

    官方规则:https://eslint.bootcss.com/docs/rules/

    "rules": {
        // 代码风格
        "array-bracket-spacing": ["error", "never"], // 方括号[]与value之间禁止空格
        "brace-style": "error", // 强制在代码块中使用一致的大括号风格
        "comma-dangle": ["error", "never"], // 禁止末尾逗号
        "comma-spacing": ["error", {"before": false, "after": true}], // 强制在逗号前后使用一致的空格
        "comma-style": ["error", "last"], // 强制在逗号前后使用一致的空格
        "indent": ["error", 2], // 使用2个空格缩进
        "jsx-quotes": ["error", "prefer-double"], // jsx中使用双引号
        "key-spacing": ["error", {"beforeColon": false, "afterColon": true}], // 在对象字面量的键和值之间使用一致的空格
        "keyword-spacing": ["error", {"before": true}], // 强制关键字周围空格的一致性
        "multiline-comment-style": ["error", "starred-block"], // 强制对多行注释使用特定风格
        "no-multiple-empty-lines": "error", // 不允许多个空行,默认最多两个
        "object-curly-spacing": ["error", "never"], // 强制在花括号中使用一致的空格
        "quotes": ["error", "double"], // 强制使用双引号
        "space-before-blocks": "error", // 要求语句块之前的空格
        "space-before-function-paren": ["error", "never"], // 禁止函数圆括号之前有一个空格
        "space-in-parens": ["error", "never"], // 禁止圆括号内的空格
        "space-infix-ops": "error", // 要求中缀操作符周围有空格
        "spaced-comment": ["error", "always"], // 要求在注释前有空白
        "switch-colon-spacing": "error", // 强制在 switch 的冒号左有空格, 右无空格
        "semi": ["error", "always"] // 要求使用分号
      }
    

    prettier(可选,需要与eslint的配置保持一致,防止冲突)

    1. 安装
    yarn add prettier -D
    
    2. 根目录新建.prettierrc.js配置文件
    module.exports = {
      semi: true,
      singleQuote: false
    }
    
    3. vscode安装prettier插件,setting.json添加如下配置,保存时可自动修复;

    注意与eslint配置保持一致,防止冲突

    // setting.json
    "[javascript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[html]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    
    
    5. 配置

    官方配置:https://prettier.io/docs/en/options.html

    相关文章

      网友评论

          本文标题:安装eslint和prettier

          本文链接:https://www.haomeiwen.com/subject/gbnbrrtx.html