一、安装eslint相关依赖
`npm install eslint eslint-config-airbnb-base babel-eslint eslint-plugin-import eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-html --save-dev`
二、配置eslint文件
放在项目根目录下
.eslintrc.js文件配置信息
module.exports = { env: { browser: true, node: true, es6: true, }, plugins: [ 'react', 'react-hooks', ], parser: 'babel-eslint', // include eslint-plugin-import parserOptions: { ecmaVersion: 7, sourceType: 'module', ecmaFeatures: { jsx: true, modules: true, } }, extends: 'airbnb-base', rules: { // off 'no-use-before-define': 0, 'no-console': 0, 'no-alert': 0, 'no-plusplus': 0, 'no-unused-expressions': 0, 'func-names': 0, 'eqeqeq': 0, 'no-underscore-dangle': 0, 'no-param-reassign': 0, 'no-new': 0, 'import/no-unresolved': 0, 'import/no-extraneous-dependencies': 0, 'linebreak-style': 0, 'no-nested-ternary': 0, 'arrow-body-style': 0, 'prefer-const': 0, // warn 'import/prefer-default-export': 1, 'no-unused-vars': 1, // error indent: [2, 4, { SwitchCase: 1, VariableDeclarator: 1, outerIIFEBody: 1, FunctionDeclaration: { parameters: 1, body: 1, }, FunctionExpression: { parameters: 1, body: 1, }, }], 'space-before-function-paren': [2, 'never'], 'wrap-iife': [2, 'inside', { functionPrototypeMethods: true }], 'max-len': [2, 120, 4, { ignoreUrls: true, ignoreComments: false, ignoreRegExpLiterals: true, ignoreStrings: true, ignoreTemplateLiterals: true, }], // react 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2, 'react-hooks/rules-of-hooks': 2, // 使用后会添加不希望出现的变量到依赖 // 'react-hooks/exhaustive-deps': 1, // no debugger 'no-debugger': 2, }};
.eslintignore文件配置信息
dist/***/node_modules/*
三、添加vscode设置
vscode安装插件eslint
ctrl+P输入setting,打开setting.json
添加以下参数
{ // vscode默认启用了根据文件类型自动设置tabsize的选项 "editor.detectIndentation": false, // 重新设定tabsize "editor.tabSize": 4, // #每次保存的时候自动格式化 "editor.formatOnSave": true, // #每次保存的时候将代码按eslint格式进行修复 "eslint.autoFixOnSave": true, // 添加 vue 支持 "eslint.validate": [ "javascript", "javascriptreact", { "language": "vue", "autoFix": true } ], // #让prettier使用eslint的代码格式进行校验 "prettier.eslintIntegration": true, // #去掉代码结尾的分号 "prettier.semi": false, // #使用带引号替代双引号 "prettier.singleQuote": true, // #让函数(名)和后面的括号之间加个空格 "javascript.format.insertSpaceBeforeFunctionParenthesis": true, // #这个按用户自身习惯选择 "vetur.format.defaultFormatter.html": "js-beautify-html", // #让vue中的js按编辑器自带的ts格式进行格式化 "vetur.format.defaultFormatter.js": "vscode-typescript", "vetur.format.defaultFormatterOptions": { "js-beautify-html": { "wrap_attributes": "force-aligned" // #vue组件中html代码格式化样式 } }, // 格式化stylus, 需安装Manta's Stylus Supremacy插件 "stylusSupremacy.insertColons": false, // 是否插入冒号 "stylusSupremacy.insertSemicolons": false, // 是否插入分好 "stylusSupremacy.insertBraces": false, // 是否插入大括号 "stylusSupremacy.insertNewLineAroundImports": false, // import之后是否换行 "stylusSupremacy.insertNewLineAroundBlocks": false, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "files.autoSave": "off" // 两个选择器中是否换行}
四、重启vscode
重启vscode之后,测试保存有没有自动格式化。如果提示配置冲突,选yes就行