Vue的代码规范和配置

集成editorconfig配置

EditorConfig可以让不同系统电脑,或者不同IDE编辑器中,让不同的开发者保持一致的编码风格,Vue官方的editorconfig内容如下

js 复制代码
# https://editorconfig.org

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
  • charset 设置文件的字符集
  • indent_style 缩进风格
  • indent_size 缩进大小
  • end_of_line 换行类型 (lf | cr | crlf)
  • insert_final_newline 始终在文件末尾插入一个新行
  • trim_trailing_whitespace 去除行首的任意空白字符

VSCode需要安装一个插件:EditorConfig for VS Code

使用prettier工具

Prettier是一款强大的代码格式化工具,基本上前端用到的文件格式它都可以搞定

1、install:npm install prettier -D 2、配置 .prettierrc 文件

js 复制代码
{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false
}
  • useTabs: 使用tab缩进还是空格缩进
  • tabWidth:tab是空格的情况下,是几个空格
  • printWidth:当前行字符的长度
  • singleQuote:使用单引号还是双引号,选择true,使用单引号
  • trailingComma:在多行输入的尾逗号是否添加
  • semi:语句末尾是否要加分号,默认值true,选择false表示不加

3、创建 .prettierignore 忽略文件

js 复制代码
/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*
/.npmrc/**

4、需要在VSCode中安装prettier插件 『Prettier - Code formatter』 5、代码格式化: 可以在package.json 的script脚本下配置

json 复制代码
"prettier": "prettier --write ."

使用 npm run prettier,会找到 node_modules下的.bin目录下的prettier工具格式化项目里的所有文件(prettierignore里配置的忽略文件不会被格式化)

使用ESLint检测

1、创建Vue项目的时候,如果选择了ESLint,Vue会默认帮我们配置需要的ESLint环境 2、VSCode需要安装ESLint插件 3、解决eslint和prettier冲突的问题

arduino 复制代码
安装插件:npm install eslint-plugin-prettier eslint-config-prettier -D

如果在创建Vue项目时选择了prettier,那么这两个插件会自动安装 4、添加prettier插件

json 复制代码
extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    'plugin:prettier/recommended'
  ],

添加的就是'plugin:prettier/recommended'这一行。

Note:我的实际操作中,保存文件的时候prettier一直没有生效,后来发现是之前安装了Volar插件,某些情况下会接管部分格式化的功能,这时vscode里存在两种格式化的方案。我的处理方式是把prettier设置成默认格式化方式:

  1. Command+Shift+P调出命令面板,输入format document with......
  2. 选择配置默认格式化程序
  3. 选择到prettier

相关截图:

或者可以在 settings.json 的工作区设置中添加如下配置:

json 复制代码
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"volar.format.enable": false, // 禁止 Volar 进行格式化
"[vue]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
}
相关推荐
扯蛋4381 天前
LangChain的学习之路( 一 )
前端·langchain·mcp
Mr.Jessy1 天前
Web APIs学习第一天:获取 DOM 对象
开发语言·前端·javascript·学习·html
ConardLi1 天前
Easy Dataset 已经突破 11.5K Star,这次又带来多项功能更新!
前端·javascript·后端
冴羽1 天前
10 个被严重低估的 JS 特性,直接少写 500 行代码
前端·javascript·性能优化
rising start1 天前
四、CSS选择器(续)和三大特性
前端·css
一 乐1 天前
高校后勤报修系统|物业管理|基于SprinBoot+vue的高校后勤报修系统(源码+数据库+文档)
java·前端·javascript·数据库·vue.js·毕设
爱喝水的小周1 天前
《UniApp 页面配置文件pages.json》
前端·uni-app·json
mapbar_front1 天前
React中useContext的基本使用和原理解析
前端·react.js
贪婪的君子1 天前
【每日一面】实现一个深拷贝函数
前端·js
_安晓1 天前
Rust 中精确大小迭代器(ExactSizeIterator)的深度解析与实践
java·前端·python