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"
}
相关推荐
小小小小宇5 小时前
前端并发控制管理
前端
小小小小宇5 小时前
前端SSE笔记
前端
小小小小宇5 小时前
前端 WebSocket 笔记
前端
小小小小宇6 小时前
前端visibilitychange事件
前端
小小小小宇7 小时前
前端Loader笔记
前端
烛阴8 小时前
从0到1掌握盒子模型:精准控制网页布局的秘诀
前端·javascript·css
前端工作日常11 小时前
我理解的`npm pack` 和 `npm install <local-path>`
前端
李剑一12 小时前
说个多年老前端都不知道的标签正确玩法——q标签
前端
嘉小华12 小时前
大白话讲解 Android屏幕适配相关概念(dp、px 和 dpi)
前端
姑苏洛言12 小时前
在开发跑腿小程序集成地图时,遇到的坑,MapContext.includePoints(Object object)接口无效在组件中使用无效?
前端