在最新的项目使用到了vue3和Typescript,基于这个还要是代码更规范,使用ESLint + Prettier 来统一代码格式化,并且保存时自动进行格式修正。 所用到环境及插件:
- vscode
- vue-cli
- typescript
- eslint
- prettier
创建新项目
vue create vue-ts
注意在创建项目过程中,需要勾选 ESLint + Prettier,并且在最后 选择 Lint on save 和 In decicated config files
安装 ESLint 和 Prettier
安装ESLint:
npm i -D eslint eslint-plugin-vue @typescript-eslint/parser @typescript-eslint/eslint-plugin
安装Prettier:
npm i -D prettier eslint-config-prettier eslint-plugin-prettier
修改 .eslintrc.js
规则可以自己配置,我主要修改了extends:
- @typescript-eslint/parsar:ESLint的解析器,用于解析 Typescript,从而检查和规范 Typescript 代码。
- @vue/prettier/@typescript-eslint:使得@typescript-eslint 中的样式规范失效,遵循prettier 中的样式规范
- extends:代表你启动哪些 lint 选项,如果多个规则直接有冲突的话,extends后面的选项会覆盖前面的。 .eslintrc.js的内容如下:
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'@vue/prettier',
'@vue/prettier/@typescript-eslint',
'plugin:prettier/recommended'
],
parserOptions: {
parsar: '@typescript-eslint/parsar',
ecmaVersion: 2020,
sourceType: 'module'
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
在根目录下添加 .prettierrc.js 文件
.prettier.js 的文件内容如下:
module.exports = {
printWidth: 120, // 换行字符串阈值
tabWidth: 2, // 设置工具每一个水平缩进的空格数
useTabs: false,
semi: false, // 句末是否加分号
vueIndentScriptAndStyle: true,
singleQuote: true, // 用单引号
trailingComma: 'none', // 最后一个对象元素符加逗号
bracketSpacing: true,
jsxBracketSameLine: true, // jsx > 是否另取一行
arrowParens: 'always', // 不需要写文件开头的 @prettier
insertPragma: false, // 不需要自动在文件开头加入 @prettier
endOfLine: 'lf' // 换行符使用 lf
}
以上就是项目格式化的配置,最后还需要对vscode软件的settings.json文件进行配置。配置内容如下:
{
"editor.fontSize": 20, // 编辑器字体大小
"terminal.integrated.fontSize": 18, // terminal 框的字体大小
"editor.tabSize": 2, // Tab 的大小 2个空格
"editor.formatOnSave": true, // 保存是格式化
"prettier.singleQuote": true, // 单引号
"editor.defaultFormatter": "esbenp.prettier-vscode",
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.format.enable": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"html",
"vue",
"typescript",
"typescriptreact"
],
}
注意
最后,还需要重启vscode,重新打开项目,至此项目就可以在保存代码时按照你项目里配置的格式化规则进行自动格式化了。