从0-1搭vue3前端后进了精神病院(4)-- eslint

185 阅读4分钟

只介绍selint的引入和基本配置,详细更多的配置项不会一一介绍,根据需求前往eslint官网进行学习与配置。

npm install eslint --save-dev

接下来网上有两种配置方式,一种是挨个手动npm下载(自行百度网上很多),还有一种使用命令配置自动创建,我比较懒选择简单的初始化eslint选择的方式

// 输入初始化指令
npx eslint --init

// 选择模式:第三个严格的模式,方向键选择回车
? How would you like to use ESLint? … 
  To check syntax only
  To check syntax and find problems
❯ To check syntax, find problems, and enforce code style

// 模块方式:选es6的啊,年轻人谁还会amd cmd呢??
? What type of modules does your project use?  JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these

//选择语言框架:emmmm
? Which framework does your project use? … 
  ReactVue.js
  None of these
  
// 是否使用ts:emmmm
? Does your project use TypeScript? › No / Yes
  
  
// 代码的运行环境?如果都需要可以选择空格按空格键选中,或者a全选,
// 我是都选了,browser浏览器,node中
? Where does your code run? …  (Press <space> to select, <a> to toggle all, <i> to invert selection)
✔ BrowserNode


//喜欢的风格:随便
? How would you like to define a style for your project? … 
❯ Use a popular style guide
  Answer questions about your style

// 你想遵循哪一种风格指南? 用过Airbnb,太严格了,喜欢严谨的可以用,
// 我是跟着别人用了第二个,试试水,不行再改
? Which style guide do you want to follow? … 
  Airbnb: https://github.com/airbnb/javascriptStandard: https://github.com/standard/standard
  Google: https://github.com/google/eslint-config-google
  XO: https://github.com/xojs/eslint-config-xo

// 你希望你的配置文件是什么格式的文件,目前我遇见的项目都是js
? What format do you want your config file to be in? … 
❯ JavaScript
  YAML
  JSON
 
// 选完后登一会然后就能看到会给你下载的各个插件了,如果选择第一种方法的,
// 就是这样挨个去下,然后需要配置的再去配置,选择yes 立即下载
Checking peerDependencies of eslint-config-standard@latest
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest @typescript-eslint/eslint-plugin@latest eslint-config-standard@latest eslint@^8.0.1 eslint-plugin-import@^2.25.2 eslint-plugin-n@^15.0.0 eslint-plugin-promise@^6.0.0 @typescript-eslint/parser@latest
? Would you like to install them now? › No / Yes

// 想用什么方式下载这些包,看个人喜好,看自己本地用的,我选的npm
? Which package manager do you want to use? … 
❯ npm
  yarn
  pnpm

最后我的配置清单,rules看个人可以去自己官网配,或者复制这一份,开发过程觉得有些烦到了,再注视掉就好。

module.exports = {
    root: true,
    env: {
        node: true,
    },
    extends: [
        'plugin:vue/vue3-essential',
        '@vue/typescript/recommended',
    ],
    parserOptions: {
        ecmaVersion: 2020,
    },
    globals: {
        hex_md5: true,
        WordList: true,
        paypal: true,
        Stripe: true,
        Lang: true,
        langOptions: true,
        ChangeWordList: true,
        SmartHomeWordList: true,
    },
    rules: {
        indent: 'off',
        '@typescript-eslint/indent': ['warn', 4],
        '@typescript-eslint/ban-ts-comment': 'off',
        '@typescript-eslint/no-non-null-assertion': 'off',
        '@typescript-eslint/no-explicit-any': 'off',
        'no-param-reassign': 'off',
        'import/prefer-default-export': 'off',
        'vue/html-indent': ['warn', 4],
        'max-len': ['warn', 150],
        'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
        "@typescript-eslint/ban-types": [
            "error",
            {
                types: {
                    Function: false
                },
                extendDefaults: true
            }
        ],
        semi: [2, 'always'], // 强制语句分号结尾
        'vue/multi-word-component-names': 'off',
        'default-case': 'error', // 强制switch要有default分支
        'eqeqeq': 'error', // 要求使用 === 和 !==
        'no-multi-spaces': 'error', // 禁止出现多个空格,如===前后可以有一个空格,但是不能有多个空格
        'no-useless-concat': 'error', // 禁止没有必要的字符串拼接,如'a'+'b'应该写成'ab'
        'require-await': 'error', // 禁止使用不带await的async表达式
        'block-spacing': 'error', // 强制函数/循环等块级作用域中的花括号内前后有一个空格(对象除外)
        'computed-property-spacing': 'error', // 禁止在计算属性中出现空格,如obj[ 'a' ]是错的,obj['a']是对的
        'func-call-spacing': 'error', // 禁止函数名和括号之间有个空格
        'key-spacing': 'error', // 强制对象键值冒号后面有一个空格
        // 'newline-per-chained-call': ['error', { 'ignoreChainWithDepth': 2 }], // 链式调用长度超过2时,强制要求换行
        'no-multiple-empty-lines': 'error', // 限制最多出现两个空行
        'no-trailing-spaces': 'error', // 禁止在空行使用空白字符
        'no-unneeded-ternary': 'error', // 禁止多余的三元表达式,如a === 1 ? true : false应缩写为a === 1
        'no-whitespace-before-property': 'error', // 禁止属性前有空白,如console. log(obj['a']),log前面的空白有问题
        'object-property-newline': ['error', { 'allowAllPropertiesOnSameLine': true }], // 强制对象的属性在同一行或全换行
        'semi-spacing': 'error', // 强制分号后面有空格,如for (let i=0; i<20; i++)
        'semi-style': 'error', // 强制分号出现在句末
        'space-infix-ops': 'error', // 强制操作符(+-/*)前后有一个空格
        'spaced-comment': 'error', // 强制注释(//或/*)后面要有一个空格
        'arrow-spacing': 'error', // 要求箭头函数的=>前后有空格
        'no-var': 'error', // 要求使用let或const,而不是var
        'prefer-const': 'error', // 要求使用const声明不会被修改的变量
        'comma-spacing': 'error', // 要求在逗号后面加个空格,禁止在逗号前面加一个空格
        'object-curly-spacing': ['error', 'always'],
    },
    overrides: [
        {
            files: [
                '**/__tests__/*.{j,t}s?(x)',
                '**/tests/unit/**/*.spec.{j,t}s?(x)',
            ],
            env: {
                jest: true,
            },
        },
    ],
};

package.json加一句lint的命令

 "scripts": {
    "serve": "npm run dev",
    "dev": "vite",
    "build": "vue-tsc --noEmit && vite build",
    "preview": "vite preview",
    // 加这句
    "lint:eslint": "eslint --cache --max-warnings 0  "{src,mock}/**/*.{vue,ts,tsx}" --fix"
  },

然后我们运行下命令

npm run lint:eslint

就能看出与配置不符合的报错了 然后挨个修改,或者配置下lint自动修复命令,前期是我们刚搭建可以,后期如果你是对一个已经有悠久历史的项目,还是最好挨个改