插件介绍
ESLint:是JavaScript和JSX检查工具prettier:代码格式化工具
依赖安装
#安装 eslint
`npm install --save-dev eslint eslint-plugin-vue
`#安装 prettier
`npm install --save-dev prettier eslint-plugin-prettier @vue/eslint-config-prettier`
#安装 typescript 支持
`npm install --save-dev @vue/eslint-config-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser`
复制代码
配置文件
1. 根目录新建 .eslintrc.js 文件
// 根据配置自行配置 官方中文网:https://zh-hans.eslint.org/docs/latest/
module.exports = {
root: true,
env: {
browser: true,
// 必填
node: true,
es2021: true,
},
parser: 'vue-eslint-parser',
extends: [
'eslint:recommended',
'plugin:vue/vue3-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
// eslint-config-prettier 的缩写
'prettier',
],
parserOptions: {
ecmaVersion: 12,
parser: '@typescript-eslint/parser',
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
// eslint-plugin-vue @typescript-eslint/eslint-plugin eslint-plugin-prettier的缩写
plugins: ['vue', '@typescript-eslint', 'prettier'],
rules: {
'prettier/prettier': [
'error',
{
singleQuote: true,
semi: true,
printWidth: 100,
},
],
'no-undef': 'off',
'vue/v-on-event-hyphenation': 0, // html上的事件允许驼峰格式phoneCallback
'vue/no-v-html': 'off',
// 注意你必须禁用基本规则,因为它可以报告不正确的错误
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'off',
// 关闭名称校验
'vue/multi-word-component-names': 'off',
},
// Vue3.0提示报错未结构以下模块问题; Vue3.2以上版本不在需要结构
globals: {
defineProps: 'readonly',
defineEmits: 'readonly',
defineExpose: 'readonly',
withDefaults: 'readonly',
},
};
2.根目录新建 .eslintignore
.vscode
.idea
.local
index.html
!.env-config.ts
components.d.ts
/node_modules/
/public/
复制代码
3.根目录新建 .prettierrc.js
// 根据配置自行配置 官方中文网:https://www.prettier.cn/docs/options.html
module.exports = {
// 一行最多 100 字符
printWidth: 100,
// 使用 2 个空格缩进
tabWidth: 4,
// 不使用缩进符,而使用空格
useTabs: false,
// 行尾需要有分号
semi: true,
// 使用单引号
singleQuote: true,
// 对象的 key 仅在必要时用引号
quoteProps: 'as-needed',
// jsx 不使用单引号,而使用双引号
jsxSingleQuote: false,
// 末尾不需要逗号
trailingComma: 'all',
// 大括号内的首尾需要空格
bracketSpacing: true,
// jsx 标签的反尖括号需要换行
jsxBracketSameLine: false,
// 箭头函数,只有一个参数的时候,也需要括号
arrowParens: 'always',
// 每个文件格式化的范围是文件的全部内容
rangeStart: 0,
rangeEnd: Infinity,
// 不需要写文件开头的 @prettier
requirePragma: false,
// 不需要自动在文件开头插入 @prettier
insertPragma: false,
// 使用默认的折行标准
proseWrap: 'preserve',
// 根据显示样式决定 html 要不要折行
htmlWhitespaceSensitivity: 'css',
// 换行符使用 lf
endOfLine: 'auto',
};
复制代码
4.根目录新建 .prettierignore
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
复制代码
根目录配置 package.json文件
"lint": "eslint --fix --ext .js,.vue src"
复制代码
5.配置完成就可以使用 npm run lint 代码检查 npm run lint --fix 问题修复啦!!!!
结束语
想要在VScode中保存并自动格式化
VScode需要安装这两款插件,在settings.json中编辑
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.format.enable": true
}
复制代码
--- 再会!!!!!