前言
最近接手旧的uni-app项目,发现项目没有集成Lint工具,开发时,代码基本的语法错误都没有提示,每次都得HRM之后才能发现问题,一些隐藏的问题,也无法提前感知,痛定思痛,最后决定花点时间给项目集成Lint工具。
使用Eslint + Prettier 插件进行代码检测与格式化,以下以uni-app项目做示例:
第一章 定义规范
- 基础规范 符合eslint recommended规范 'eslint:recommended'
- vue sfc规范 符合 'plugin:vue/vue3-essential' 或者 'plugin:vue/recommended'
- 特定风格规范( prettier ):
-
- 缩进方式: tab tab宽度: 4
- 结尾换行符: crlf
- 单双引号:singleQuote
- 分号: 语句末尾分号
- 尾随逗号:es5
第二章 工具实现
Vue2、Vue3
使用npm初始化eslint配置
npm init @eslint/config
按操作选择需要的选项后eslint会安装和生成对应的包和文件
module.exports = {
'env': {
'es2021': true,
'node': true
},
'extends': [
'eslint:recommended',
'plugin:vue/vue3-essential'
],
'overrides': [
],
'parserOptions': {
'ecmaVersion': 'latest',
'sourceType': 'module'
},
'plugins': [
'vue'
],
'rules': {
'indent': [
'error',
'tab'
],
'linebreak-style': [
'error',
'windows'
],
'quotes': [
'error',
'single'
],
'semi': [
'error',
'always'
]
}
};
安装 prettier相关插件
npm install prettier eslint-config-prettier eslint-plugin-prettier -S
设置 eslint 配置, globals 配置一些全局变量,比如uni-app下的一些全局变量, ignorePatterns用于忽略一些uniapp生成的目录文件的检测
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/recommended',
'plugin:prettier/recommended',
],
overrides: [],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['vue'],
rules: {
'no-underscore-dangle': 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-unused-vars': 'warn',
'vue/component-name-in-template-casing': ['warn', 'kebab-case'],
'vue/multi-word-component-names': 'off',
'prefer-destructuring': 'off',
'no-plusplus': 'off',
},
globals: {
uni: 'readonly',
plus: 'readonly',
getCurrentPages: 'readonly',
getApp: 'readonly',
},
ignorePatterns: ['./pages.json', 'uni_modules', 'unpackage'],
};
Vu2与Vue3区别一下 对应不同的eslint plugin
module.exports = {
extends: [
// add more generic rulesets here, such as:
// 'eslint:recommended',
'plugin:vue/vue3-recommended',
// 'plugin:vue/recommended' // Use this if you are using Vue.js 2.x.
],
rules: {
// override/add rules settings here, such as:
// 'vue/no-unused-vars': 'error'
}
}
设置prettier配置
{
"tabWidth": 4,
"useTabs": true,
"endOfLine": "crlf",
"singleQuote": true,
"semi": true,
"trailingComma": "es5",
"bracketSpacing": true
}
vscode 配置
{
"path-intellisense.mappings": {
"@": "${workspaceFolder}"
},
"path-autocomplete.pathMappings": {
"@": "${workspace}"
},
// "editor.formatOnSave": true,
"eslint.format.enable": true,
// "eslint.packageManager": "npm",
// "eslint.run": "onSave",
// "eslint.validate": ["vue", "javascript", "javascriptreact", "json"],
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}