zoukankan      html  css  js  c++  java
  • eslint+prettier学习

    eslint学习

    配置文件:.eslintrc.js

    常见配置字段

    module.exports = {
      'parser':'esprima',
      'env': {
        'browser': true,
        'es6': true,
      },
      'extends': [
        'airbnb',
      ],
      'globals': {
        'Atomics': 'readonly',
        'SharedArrayBuffer': 'readonly',
      },
      'parserOptions': {
        'ecmaVersion': 2018,
        'sourceType': 'module',
        'ecmaFeatures': {
            'jsx': true
         }
      },
      'rules': {
        'semi': 'error'
      },
    };

    配置字段解析

    详情参考文档

    extends:[]

    配置文件可以从基本配置扩展启用的规则集,不添加则不会继承任何扩展集,仅按照rules下的基本配置来执行。

    可以扩展的规则常见的有:

    airbnb(世界第一)

    安装依赖包

    npm install eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-import eslint-config-airbnb --save
    
    {
    "extends": "airbnb" }

    规则特点

    不去掉分号

    自动把import引入的包放在了最上面

    不希望有console,有会报警告

    if语句如果没有包大括号不会加大括号,会从两行转为一行

    多个import后面加一个空行

    字符串使用单引号

    缩进为2个空格

    未定义的变量会报错

    箭头函数前后需要空格

    未使用的变量会报错

    standard(世界第二)

    安装依赖包

    npm install --save-dev eslint-config-standard eslint-plugin-standard eslint-plugin-promise eslint-plugin-import eslint-plugin-node
    
    {
    "extends": "standard" }

    规则特点

    去掉分号

    if语句会自动加大括号,两行转为一行

    缩进2个空格

    字符串使用单引号

    自动把import引入的包放在了最上面

    多个Import之间有空行,最后一个import之后不会有空行

    未定义的变量会报错

    箭头函数前后需要空格

    未使用的变量会报错

    alloy(世界第三)

    AlloyTeam ESLint 规则不仅是一套先进的适用于 React/Vue/Typescript 项目的 ESLint 配置规范,而且也是你配置个性化 ESLint 规则的最佳参考。腾讯开源eslint规则,目前主要是对代码规则的校验,不包含格式校验。

    npm install --save-dev eslint babel-eslint eslint-config-alloy
    module.exports = {
      extends: [
        'alloy',
      ],
      env: {
        // Your environments (which contains several predefined global variables)
        //
        // browser: true,
        // node: true,
        // mocha: true,
        // jest: true,
        // jquery: true
      },
      globals: {
        // Your global variables (setting to false means it's not allowed to be reassigned)
        //
        // myGlobal: false
      },
      rules: {
        // Customize your rules
      },
    };

    google

    安装依赖包

    npm install --save-dev eslint-config-google

    规则特点

    不去掉分号

    字符串使用单引号

    相对上面两个力度较小,import没有自动提到最上面,

    未定义的变量不会报错

    缩进为2个空格

    箭头函数前后没有空格要求

    未使用的变量会报错

    eslint:recommended

    粒度比较小,依然支持双引号,也没有空格,仅报错了未定义的变量和未使用的变量

    eslint:all

    粒度相当大,各种空行,console.log里都是换行,if语句里面都是空行,import不会提到前面

    plugin:prettier/recommended

    即prettier规则。

    使用此规则的方式见下面 :eslint+prettier配合配置 

    大概看出的几个共同点

    都会把没有改变过的变量从let定义改为const定义

    字符串都转为单引号

    该有的空格都有

    未使用的变量会报错 

    严格程度排名

    airbnb>standard>alloy>google

     

    plugins:[]

    ESLint支持使用第三方插件。在使用插件之前,您必须使用npm安装它。

    插件:

    eslint-plugin-html

    一个ESLint插件,用于整理和修复HTML文件中包含的内联script脚本,支持多个script标签,此行为不适用于“模块”脚本(即:<script type="module">)

    https://www.npmjs.com/package/eslint-plugin-html

    配置方式:

    在 .eslintrc.js中的plugin中加入html

    {
        "plugins": [
            "html"
        ]
    }

    rules:[]

    配合代码规则:

    • "off"0-关闭规则
    • "warn"1-将该规则作为警告打开(不影响退出代码)
    • "error"2-将规则作为错误打开(触发时退出代码为1)

    parserOptions:{}

    解析器选项,主要用于解析JavaScript的语言选项

    ecmaVersion:JavaScript版本

    sourceType:script还是module

     

    eslint常用几个命令

    eslint --init  **/*.js     初始化创建默认eslint配置

    eslint --fix **/*.js       修复问题

    注意:使用项目中的eslint,命令为    npx eslint --fix **/*.js  

     

     

    webpack eslint配置

    {
      test: /.js$/,
        use: [
          {
            loader: "babel-loader",
          },
          {
            loader: "eslint-loader",// 这里的配置项参数将会被传递到 eslint 的 CLIEngine
            options: {
              fix: true,// 保存自动格式化开启
              formatter: require('eslint-friendly-formatter') // 指定错误报告的格式规范
            }
          },
        ],
          enforce: "pre",
          include: [path.resolve(__dirname, 'src')], // 指定检查的目录
      },
     

    prettier学习

    作用

    prettier 主要是为了格式化代码,而在没有 prettier 之前,是用 eslint —fix和 编辑器自带代码格式来进行代码格式化的。

    • 缺点:每种编辑器会有不一样的代码格式,而且配置会比较麻烦。
    • prettier 已经逐渐成为业界主流的代码风格格式化工具。
    • 减轻 eslint 等工具的校验规则,因为将代码样式校验交给了 prettier,所以可以将代码校验的规则更准确地应用到代码真正的规范上面。

     

    安装

    First, install Prettier locally:

    prettier需要精确安装,

    npm install --save-dev --save-exact prettier

    Then, create an empty config file to let editors and other tooling know you are using Prettier:

    echo {}> .prettierrc.json​ 

    Next, create a .prettierignore file to let the Prettier CLI and editors know which files to not format. Here’s an example:

    # Ignore artifacts:

    build
    coverage

    命令

    prettier --check **/*.js

    prettier --write **/*.js

    注意:使用项目中的eslint,命令为 npx prettier --write **/*.js

     

    eslint+prettier配合配置

    eslint 是主要还是负责代码规则校验,prettier 只调整代码风格,代码样式,eslint 才是真正检查代码是否符合规范的工具。两者分工不同,所以需要配合使用。

     

    了解配合配置的方式,先来了解几个npm包

    插件:

    eslint-plugin-prettier

    作用:一个形式上跟standard类似的一个代码规则,用来在基础规则上扩展的规则,eslint的rules规则优先级大于prettier的规则。

    提示:eslint-plugin-prettier不会为您安装Prettier或ESLint,你必须自己安装。

    使用prettier的扩展规则有两种方式:

    注意:不需要写extends:"prettier",光下面的配置即可

    方式一:

    {
      "plugins": ["prettier"],
      "rules": {
        "prettier/prettier": "error"
        // "prettier/prettier": ["error", {"singleQuote": true, "parser": "flow"}] 这里的配置会覆盖.prettierrc.js的配置
        // "prettier/prettier": ["error", {}, {
        //      "usePrettierrc": true
            //  }] // 开启这个配置,可以指定使用.prettierrc.js配置,不会和其他配置冲突
      }
    }

    方式二:

    extends: [
        'plugin:prettier/recommended',
    ],

    两种区别:

    方式一:两种规则会有冲突

    方式二:两种规则没有冲突,会自动去掉eslint冲突的规则,配置简单。

    重点:

    如果使用方式二,需配合 eslint-config-prettier

    作用:禁用与lint相关的所有格式化规则。

    注意:

    由于编辑器等自动格式化配置设置了走.prettierrc.js文件,建议写覆盖的配置,写在这里,不要写在.eslintrc.js配置中,否则可能得不到想要的结果。

    安装插件:

    注意:为了避免不同人安装的的prettier版本不同导致的代码格式化规则不同,建议安装prettier使用精确版本安装。

    npm install --save-dev --save-exact prettier 
    npm install --save-dev eslint-plugin-prettier eslint-config-prettier

    规则冲突示例:

    可以看到同一行的同样的错误会抛出两个版本的错误信息

    3:19  error  Replace `"axios"` with `'axios';`  prettier/prettier // prettier抛出
    3:19  error  Strings must use singlequote       quotes   // esLint抛出

    使用方式二后,prettier的规则会覆盖掉standard相同的规则

    最终配置

    样式格式校验

    stylelint

    npm install stylelint --save-dev

    stylelint-config-prettier

    npm install --save-dev stylelint-config-prettier

    Then, append stylelint-config-prettier to the extends array in your .stylelintrc.* file. Make sure to put it last, so it will override other configs.

    {
      "extends": [
        // other configs ...
        "stylelint-config-prettier"
      ]
    }
     

    stylelint-config-recommended

    所有样式问题都会暴露

    npm install stylelint-config-recommended --save-dev

     

    stylelint-config-standard

    stylelint-config-standard是stylelint的推荐配置

    stylelint-order是 css 属性排序插件

    npm install stylelint-config-standard --save-dev

    stylelint-order

    npm install stylelint-order --save-dev
    {
        "plugins": [
            "stylelint-order"
        ],
        "rules": {
            "order/order": [
                "custom-properties",
                "declarations"
            ],
            "order/properties-order": [
                "width",
                "height"
            ]
        }
    }

    代码检查

    npx stylelint "**/*.css"

     

    .eslintrc.js

    module.exports = {
        extends: [
            'alloy',
            'plugin:prettier/recommended',
        ],
        parserOptions: {
            parser: 'babel-eslint',
            sourceType: 'module',
        },
        // parser: '@typescript-eslint/parser',
        // plugins: ['@typescript-eslint'],
        rules: {
            // "prettier/prettier": "error", 
        },
        env: {
            browser: true,
            node: true,
            jest: true,
            es2017: true,
        },
        // plugins: ['html', 'prettier'],
        plugins: ['html'],
    }

    .prettierrc.js

    module.exports = {
        // 一行最多 80 字符
        printWidth: 80,
        // 使用 4 个空格缩进
        tabWidth: 4,
        // 不使用缩进符,而使用空格
        useTabs: false,
        // 行尾需要有分号
        semi: false,
        // 使用单引号
        singleQuote: true,
        // 对象的 key 仅在必要时用引号
        quoteProps: 'as-needed',
        // jsx 不使用单引号,而使用双引号
        jsxSingleQuote: false,
        // 末尾不需要逗号
        trailingComma: 'none',
        // 大括号内的首尾需要空格
        bracketSpacing: true,
        // jsx 标签的反尖括号需要换行
        jsxBracketSameLine: false,
        // 箭头函数,只有一个参数的时候,也需要括号
        arrowParens: 'always',
        // 每个文件格式化的范围是文件的全部内容
        rangeStart: 0,
        rangeEnd: Infinity,
        // 不需要写文件开头的 @prettier
        requirePragma: false,
        // 不需要自动在文件开头插入 @prettier
        insertPragma: false,
        // 使用默认的折行标准
        proseWrap: 'preserve',
        // 根据显示样式决定 html 要不要折行
        htmlWhitespaceSensitivity: 'css',
        // 换行符使用 lf
        endOfLine: 'lf'
    };

    .stylelintrc.js

    module.exports = {
        extends: [
            'stylelint-config-standard',
            'stylelint-config-prettier',
            'stylelint-config-sass-guidelines',
        ],
        plugins: [
            'stylelint-order',
            'stylelint-scss'
        ],
        rules: {
            "order/order": [
                "custom-properties",
                "declarations"
            ],
            "order/properties-order": [
                "width",
                "height"
            ]
        }
    };

    如果不用scss,建议直接这样配置:

    scss的一些规则会和常规使用的规则不太一样。

    module.exports = {
        extends: ['stylelint-config-standard'],
        // "plugins": [
        //     // "stylelint-csstree-validator"
        // ],
        rules: {
            'color-named': ['never',{ignoreProperties: ['background','color']}], // never  强制使用十六进制,always-where-possible 强制使用单词命名
            // "csstree/validator": true, // 检查属性值和属性名是否正确
            'string-quotes':'double', // double 双引号,single,单引号
            // 'block-opening-brace-newline-after':'always-multi-line' // 大括号后是否另一一行
        }
    }

    参考链接

    https://juejin.im/post/6844903621805473800

    https://juejin.im/post/6844903843541549063

    https://segmentfault.com/a/1190000022881634 【好文推荐】https://juejin.im/post/6844903832485363720【好文推荐】

    https://github.com/AlloyTeam/eslint-config-alloy/blob/master/README.zh-CN.md

    https://prettier.io/

    https://eslint.org/

    https://stylelint.io/

     

  • 相关阅读:
    zookeeper使用和原理探究(一)
    Zookeeper基本原理
    论照顾小孩与项目管理
    perl启动后台进程
    Oracle数据库迁移
    C# 语言Pagerank两种实现
    没文化真可怕--Silverlight 列冻结
    oracle中使用SQL递归语句的例子
    Visual Studio 2010 智能跟踪文件目录
    oracle wm_concat函数的应用(多行合成一行)
  • 原文地址:https://www.cnblogs.com/beileixinqing/p/13711638.html
Copyright © 2011-2022 走看看