不知不觉中,Create React App已经从v1到了v3,今天又再一次阅读了文档,将一些常用的配置记录下来
创建App
npx
npx create-react-app my-appnpm
npm init react-app my-appnpm版本大于6可用
yarn
yarn create react-app my-apptemplate
新版Create React App提供了--template [template-name]的命令行选项
如果没有选择template,会使用默认template创建
template会被命名为cra-template-[template-name],但是你只需要在命令行输入[template-name]
你可以在npm搜索"cra-template-*"找到这些包
比如创建Typescript的应用,只需要在命令行添加--template typescript
npx create-react-app my-app --template typescript选择包管理器
CLI默认会选择yarn作为包管理工具,如果你想使用npm,你可以在命令行添加--use-npm,如:
npx create-react-app my-app --use-npm自动格式化代码
添加git钩子来使用prettier格式化代码
npm install --save husky lint-staged prettier也可以使用yarn
yarn add husky lint-staged prettierhusky可以让npm script使用githookslint-staged可以在暂存文件的时候运行脚本prettier在提交前格式化代码
添加下列字段到package.json
+ "husky": {
+ "hooks": {
+ "pre-commit": "lint-staged"
+ }
+ }接下来添加lint-staged字段到package.json
"dependencies": {
// ...
},
+ "lint-staged": {
+ "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
+ "prettier --write",
+ "git add"
+ ]
+ },
"scripts": {
现在每当你提交代码时,prettier会自动格式化代码
添加自定义环境变量
添加.env文件,在这个文件里定义的变量是自定义变量
自定义变量必须以REACT_APP_开头,如
REACT_APP_SITE_NAME=网站
在代码中可以使用process.env.REACT_APP_SITE_NAME来使用
在public/index.html文件中使用自定义变量
<title>%REACT_APP_SITE_NAME`%</title>
更多参考dotenv文档
添加Sass的支持
npm install node-sass --save
# or
yarn add node-sass
引入sass文件的时候可以通过添加SASS_PATH来使用绝对路径引入
如果你设置了SASS_PATH=node_modules:src,可以像一下方式import
@import 'styles/colors'; // 从src/styles引入
@import 'nprogress/nprogress'; // 从node_module引入
CSS Modules
约定名字为[name].module.css或者使用sass后名为[name].module.scss or [name].module.sass的文件为CSS Modules文件
在开发环境使用HTTPS
如果接口是https的,代理是http就发不过去,好在Create React App提供了这个功能(虽然chrome会提示不安全)
修改package.json中的npm start脚本
{
"start": "HTTPS=true react-scripts start"
}或者添加HTTPS=true到.env文件
绝对路径的组件引入
因为没有webpack的alias的配置,所以引入很麻烦,比如../../../Components/
现在可以在jsconfig.json或者tsconfig.json中添加配置来解决这个问题
jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
如果使用Typescript,就在tsconfig.json文件中配置
现在,就可以使用绝对路径引入了
import Button from 'components/Button';