初始化

cra版本:4.0.3

创建项目并初始化

首先需进入安装项目的目录

# 使用 cra 初始化项目,并启用 typescript 编写
create-react-app 'project name' --template typescript

# 也可以通过这两条命令创建
yarn create react-app 'project name' --template typescript
npm init react-app 'project name' --template typescript

# 进入目录
cd 'project name'

# 创建 .env 文件并添加禁止开发环境自启动浏览器命令
touch .env && echo >> BROWSER=none

# 初始化项目预览
yarn start

关于更多 .env 的配置见 advanced-configurationopen in new window

配置.gitignore

忽略/.idea/.vscode 目录。

StrictMode(严格模式)

打开 src/index.tsx 会看到 <App /> 组件被 <React.StrictMode />组件包裹了。被这个组件包裹的所有组件都会被开启严格模式检查,这个模式仅在开发模式下运行,不会影响生产构建。官方文档open in new window

安装sass

默认情况下,cli只支持使用node-sass 来完成scss 文件的编译。但是由于node-sass在国内下载速度慢,还需要进行本地编译,而在本地又会因为各种情况而导致编译失败!所以最好是使用dart-sass代替node-sass:使用npm alias安装sass

normalize CSS

// 在 index.scss 中添加给cra处理的css normalize代码
@import-normalize;

Font CSS

使用跨平台中文字体解决方案open in new window设置body -> font-family

绝对路径open in new window配置

React原生支持以src为根目录的路径匹配。

  1. css引入:如果有如下目录结构:src/aa/src/bb 那么在bb内的文件可以直接用aa/xxx.css 来引入文件;
  2. ts引入open in new windowcompilerOptions -> "baseUrl": "src";

使用styled-componentsopen in new window(可选)

安装:

# 安装依赖
yarn add styled-components

# 安装类型提示
yarn add @types/styled-components -D 
最近更新:
Contributors: untilthecore