editorconfig
官网是这么介绍EditorConfig的,“EditorConfig帮助开发人员在不同的编辑器和IDE之间定义和维护一致的编码样式.通俗一点说就是保证每个开发者的编码风格一致
首先安装EditorConfig
在代码根目录创建.editorconfig文件
# http://editorconfig.org
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false
此时要测试editorconfig是否生效,改变缩进大小为8,然后去文件中按tab键,如果缩进是8那说明editorconfig配置成功。更多配置请移步至官网
Prettier
Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具
1、安装prettier插件
2、项目中安装prettier
yarn add prettier
或者
npm install prettier -D
3、配置.prettierrc文件
-
useTabs:使用tab缩进还是空格缩进,选择false;
-
tabWidth:tab是空格的情况下,是几个空格,选择2个;
-
printWidth:当行字符的长度,推荐80,也有人喜欢100或者120;
-
singleQuote:使用单引号还是双引号,选择true,使用单引号;
-
trailingComma:在多行输入的尾逗号是否添加,设置为
none
; -
semi:语句末尾是否要加分号,默认值true,选择false表示不加;
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
4、创建.prettierignore忽略文件
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
5、脚本
创建脚本,运行脚本会对所有的非prettier忽略文件做格式化
至此,你之后保存文件的时候就会按照prettier文件定义好的格式去进行格式化
ESLint
我们使用 Eslint 做代码 lint,那么为什么还要使用 .editorconfig 呢?
eslint确实有不少editorconfig的属性,但是有些属性没有比如insert_final_newline。eslint更偏向于语法提示,而 .editorconfig 更偏向于代码风格,如缩进等
1、安装eslint插件
2、安装依赖
npm i eslint
或者
yarn add eslint
3、配置.eslintrc文件
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'plugin:prettier/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
}
这里要特别注意,如果是脚手架生成的eslint+prettier的话,这个文件不需要改
4、安装eslint和prettier冲突插件
npm i eslint-plugin-prettier eslint-config-prettier -D
5、在eslintrc文件中配置extends:'plugin:prettier/recommended'