1.重写 webpack 配置,添加别名支持
- 安装 react-app-rewired
yarn add react-app-rewired
yarn add customize-cra
- 添加配置文件,修改默认配置
根目录下添加 config-overrides.js, 内容如下
const { override, addWebpackAlias } = require('customize-cra');
const path = require('path')
module.exports = override(
addWebpackAlias({
"@": path.resolve(__dirname, 'src')
}),
);
- 修改package.json 脚本启动项
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
2. 修改tsconfig.json 添加别名支持
- 先在根目录下添加一个paths.json的文件(非常重要),内容如下
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"@/*": [
"*"
]
}
}
}
- 修改tsconfig.json文件,添加如下配置
"compilerOptions": {
...
+ "baseUrl": "src"
},
+ "extends": "./paths.json",
其实还是改了tsconfig.json的内容,但是如果直接把别名配置写在tsconfig.json中,每次运行后,文件都会恢复一下,不知道为什么
3. 遇到的坑
path-intellisence 的官方文档有这段话(不要按他说的改)
To use Path Intellisense instead of the default autocompletion, the following configuration option must be added to your settings:
{ "typescript.suggest.paths": false }
网友评论