npx create-react-app jira --template typescript
npx可以让你直接去使用npm里面的包,而不需要先安装这个包。
创建完之后,打开创建的项目可以看到,已经有一次git的commit记录,而且显示的是create-react-app这个包进行的git,已经自动把所有文件加入到git中。
npm start //打开这个项目
一般来说,如果整个项目的目录结构不复杂,文件夹的嵌套结构不深的情况下,要import文件的时候,我们会使用相对路径,但是在深层嵌套文件夹中这种用法比较不方便,所以,还有一种新的方法来解决这个问题:
在根目录下tsconfig.json这个文件中:
"compilerOptions": {
添加这个++ "baseUrl":"./src",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
就可以设置为,绝对路径会直接从src文件夹下找文件。
在一个开发团队中,每一个人的格式化配置都会有所不同,Prettier就是来解决这一问题的:
yarn add --dev --exact prettier //安装依赖
echo {}> .prettierrc.json //新建一个文件,echo就是新建文件的意思
然后再新建一个.prettierignore文件来设置不需要格式化的文件
echo {}> .prettierignore
在.prettierignore中写入:
build
coverage
然后借助Pre-commit hook让每次提交的时候都自动格式化代码
npx mrm@2 lint-staged
安装完成后,在package.json中会出现以下代码:
"devDependencies": {
"husky": "^7.0.4",
"lint-staged": "^12.3.3",
"prettier": "2.5.1"
},
"lint-staged": {
"*.{js,css,md,ts,tsx}": "prettier --write"
}
由于项目中自带eslint,prettier与eslint一起工作的时候会产生一些冲突,这里还需要安装一个依赖解决冲突:
yarn add eslint-config-prettier -D
安装完毕后,再到package.json中找到eslintConfig:
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest",
"prettier"
]
},
这样的意思是,我们用prettier的规则覆盖了一部分eslint的规则,使其不再冲突
在使用这个自动格式化包时,有可能会出现以下bug:
PS D:\acode\react全栈\jira> yarn prettier --write .
yarn run v1.22.11
$ D:\acode\react全栈\jira\node_modules\.bin\prettier --write .
[error] Invalid configuration file `.prettierrc.js`: Invalid or unexpected token
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
PS D:\acode\react全栈\jira> yarn prettier --write .
yarn run v1.22.11
$ D:\acode\react全栈\jira\node_modules\.bin\prettier --write .
[error] Invalid configuration file `.prettierrc.json`: JSON Error in D:\acode\react全栈\jira\.prettierrc.json:
[error]
[error] > 1 | ��
[error] | ^
[error]
[error] Unexpected token "�" (0xFFFD) in JSON at position 0 while parsing "��"
[error]
[error] > 1 | ��
[error] | ^
[error]
error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
解决方案是,把之前创建的prettierrc.json重命名为prettier.json,我这里这样写是有效果的。