项目搭建优化
优化一
集成editorconfig配置
序:EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的编码风格。
在你的项目根目录创建.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
在你的VSCode需要安装一个插件:EditorConfig for VS Code
优化二
使用prettier工具
Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具。
1.安装prettier
npm install prettier -D
2.创建并配置.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
}
3.创建.prettierignore忽略文件 因为我们需要格式化的东西只是我们的code其他的不需要格式化
/bulid/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
4.VSCode需要安装prettier的插件
5.VSCod中的配置
- settings =>format on save => 勾选上
- settings => editor default format => 选择 我们安装的插件名称
6.测试一下prettier是否生效
注意 如果你前面跟我一起配置完成以后 有两种测试方式第一种 故意写一下违规的代码按一下ctrl+s看看能不能保存
第二种方式命令npm run prettier
使用命令前我们需要进行最后一个配置
在package.json中配置一个scripts:
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject",
"prettier": "prettier --write ."-------加上他!!(删了文字)
},
我们使用命令 npm run prettier 如果不出意外我们的代码中不符合规范的东西就都删除了
优化三
使用ESLint检测
1.在VUE创建项目的时候,我们就选择了ESLint,所以Vue会默认帮助我们配置需要的ESLint环境;但是在react中我们就需要自己配置一下了
2.VSCode需要安装ESLint插件和npm包:
npm i eslint -D
2.1我们需要配置一下eslint 我们不用手动配置
在你的终端中输入npx eslint --init
可以打开翻译软件翻译一下意思根据自己的需要选择(下面是我的选择仅供参考)
1Need to install the following packages: y
2How would you like to use ESLint? To check syntax and find problems
3What type of modules does your project use?
4Which framework does your project use? react
5Does your project use TypeScript? y
6Where does your code run? Browser(可以多选)
7What format do you want your config file to be in? JavaScript
8Would you like to install them now? y
9Which package manager do you want to use? npm
over!!!
打开项目根目录你可以看见为你生成了一个.eslintrc.js打开我们会发现有保持why???
因为他在导出的时候用来commonjs规范 但是我们的在选择环境的时候我们选择的是浏览器环境所以会报错
我们可以在.eslintrc.js文件中的env配置中加上“node”:true
"env": {
"browser": true,
"es2021": true,
"node":true
},
3.继续配置你的eslint
3.1终端执行
npm install eslint-plugin-prettier eslint-config-prettier -D
3.2在你的.eslintrc.js中的extends中添加上他
extends: [
'plugin:prettier/recommended'
],
现在你的语法如果不符合prettier的规则他就会包错提示你 我们可以在代码中打出大量的换行看一下是不是有报错