配置路径别名 @
目标:让代码中支持以
@/xxxx
形式的路径来导入文件
操作步骤
- 安装修改 CRA 配置的包:
npm i -D @craco/craco -f
- 在项目根目录中创建 craco 的配置文件:
craco.config.js
,并添加如下代码:
const path = require('path')
module.exports = {
// webpack 配置
webpack: {
// 配置别名
alias: {
// 约定:使用 @ 表示 src 文件所在路径
'@': path.resolve(__dirname, 'src'),
},
},
}
- 在项目根目录中新建
path.tsconfig.json
,并添加如下代码:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}
- 根目录的
tsconfig.json
引入路径配置
{
+ "extends": "./path.tsconfig.json",
"compilerOptions": {
"target": "es5",
package.json
修改启动命令
"scripts": {
- "start": "react-scripts start",
- "build": "react-scripts build",
- "test": "react-scripts test",
+ "start": "craco start",
+ "build": "craco build",
+ "test": "craco test",
"eject": "react-scripts eject"
},
- 测试路径导入
import { Button } from 'antd-mobile'
+import imageNone from '@/assets/none.png'
export default function App() {
return (
<div>
<h1>极客园根组件</h1>
<Button color="primary">按钮</Button>
+ <img src={imageNone} alt="" />
</div>
)
}
- 💥重启脚手架💥