配置eslint(校验代码)
安装eslint
npm install eslint --save-d
初始化eslint
-
npm init @eslint/config -
运行命令之后需要对一些配置进行选择
* `你将怎么使用eslint? ` `(1) How would you like to use ESLint? ` `选择:To check syntax , find problems and enforce code style` `//你将怎么使用eslint? 检查语法,发现问题,并强制统一代码样式` `//项目模块类型选择` `(2) What type of modules does your project use? 选择:JavaScript modules (import/export)` `// 项目框架选择` `(3) Which framework does your project use? 选择:Vue.js` `项目中是否使用ts` `(4) Does your project use TypeScript?` `选择:NO` `代码运行在什么环境` `(5) Where does your code run? 选择:Browser` `项目代码风格` `(6)How would you like to define a style for your project` `选择: use a popular style guide` `项目编码规范` `(7)Which style guide do you want to follow` `选择: Standard` `配置文件风格选择` `(8) What format do you want your config file to be in? 选择:JavaScript` `是否选择现在安装` `(9) Would you like to install them now? 选择:Yes` `包管理器选择` `(10) Which package manager do you want to use? 选择:npm` ```
-
回车之后就会进行依赖的安装。
-
依赖成功安装之后,项目的根目录就会自动生成
.eslintrc.js配置文件module.exports = { env: { browser: true, es2021: true }, extends: ['plugin:vue/vue3-essential', 'standard'], overrides: [], parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, plugins: ['vue'], rules: { 'vue/multi-word-component-names': 'off' // 关闭 组件名没有写成驼峰式结构或 pascal中划线连接形式 的验证 } } -
在
package.json文件中script块配置lint命令--javascripttypescriptbashsqljsonhtmlcssccppjavarubypythongorustmarkdown
"script":{ "lint": "eslint . --ext .vue,.js,.ts,.jsx,.tsx --fix", } -
配置之后 在命令行输入
npm run lint, 如果有不符合代码规范的则会被发现并报错 -
如果每写一行代码就运行一次命令,效率不提高反降低,这并不是我们想要的。这时可以借助vscode的插件Eslint,实现每次保存代码时,自动执行
lint命令来修复代码的错误。-
在扩展中查找
Eslint插件,并安装使用 -
然后在 vscode 中通过文件 - 首选项 - 设置 -打开setting.json文件,添加以下配置(添加之后重启vscode使配置生效)
```"editor.codeActionsOnSave": { "source.fixAll": false, "source.fixAll.eslint": true }, ``` -
配置 prettier(美化/格式化 代码)
安装 prettier
npm init prettier --save-d
使用prettier
-
在根目录上新建
.prettierrc.js文件 -
设置以下配置
module.exports = { // 一行的字符数,如果超过会进行换行,默认为120 printWidth: 120, // 一个tab代表几个空格数,默认为2 tabWidth: 2, // 是否使用tab进行缩进,默认为false,表示用空格进行缩减 useTabs: false, // 字符串是否使用单引号,默认为false,使用双引号 singleQuote: true, // 行位是否使用分号,默认为true semi: false, // 是否使用尾逗号,有三个可选值"<none|es5|all>" trailingComma: "none", // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar } bracketSpacing: true } -
在
package.json文件中script块配置format命令{ "format": "prettier --write "./**/*.{html,vue,ts,js,json,md}"" } -
配置之后 在命令行输入
npm run format,就会对我们的代码做美化/格式化 -
和
Eslint一样,prettier在vscode上也可以通过插件Prettier - Code formatter在保存的时候自动实现美化/格式化-
在扩展中查找
Prettier - Code formatter插件,并安装使用 -
然后在 vscode 中通过文件 - 首选项 - 设置 -打开setting.json文件,添加以下配置(添加之后重启vscode使配置生效)`
// 保存的时候自动格式化 "editor.formatOnSave": true, // 默认格式化工具选择prettier "editor.defaultFormatter": "esbenp.prettier-vscode" -