
修改 CRA 的默认配置
使用 create-react-app 初始化项目
sh
# JavaScript 模板
yarn create react-app my-app
# OR
npx create-react-app my-app
# TypeScript 模板
yarn create react-app my-app --template typescript
# OR
npx create-react-app my-app --template typescript使用 react-app-rewired 和 customize-cra 方案
使用
安装依赖
sh
yarn add -D react-app-rewired customize-cra
# OR
npm install -D react-app-rewired customize-cra修改 package.json 文件
diff
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "react-app-rewired start",
+ "build": "react-app-rewired build",
+ "test": "react-app-rewired test",
}项目根目录创建 config-overrides.js
js
const { override, addWebpackAlias } = require('customize-cra')
const path = require('path')
module.exports = override(
// 配置别名
addWebpackAlias({
'@': path.resolve(__dirname, 'src')
})
)相关资料
- customize-cra Api 文档
- 在 create-react-app 中使用 antd
- 在 TypeScript 中使用 antd
- Introducing new plugins in Babel to create react app
使用 craco 方案
使用
安装依赖
sh
yarn add -D @craco/craco
# OR
npm install -D @craco/craco修改 package.json 文件
diff
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
}项目根目录创建 craco.config.js
js
const path = require('path')
module.exports = {
webpack: {
// 配置别名
alias: {
'@': path.resolve(__dirname, 'src')
}
}
}相关资料
TypeScript 模板踩坑点
CRA 创建的 TypeScript 模板中,配置别名 alias 时有坑
在 tsconfig.json 配置的 paths 字段,会在运行 start / build 命令后被 CRA 给删除,同时控制台会有如下提示和报错
sh
The following changes are being made to your tsconfig.json file:
- compilerOptions.paths must not be set (aliased imports are not supported)
Cannot find module '@/xxx'. TS2307解决方案
新建 paths.json 文件,并将 paths 的配置写入进去, paths 的配置项要与 webpack alias 配置项一致
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}再去 tsconfig.json 中使用 extends 配置引入
json
{
"extends": "./paths.json"
}相关 issues
fb 真霸道,自己不用 alias,也不让用户搞

