React 配置 @ 路径别名
第一步安装依赖
yarn add react-app-rewired customize-cra
第二步修改 package.json 配置,将 react-scripts 修改成 react-app-rewired
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" },
第三步在根目录下创建 config-overrides.js 文件
const { override, addWebpackAlias } = require("customize-cra"); const path = require("path"); module.exports = override( //增加路径别名的处理 addWebpackAlias({ '@': path.resolve('./src') }) );
第四步在 tsconfig.json 文件中加入 baseUrl 和 paths
{ "compilerOptions": { "baseUrl": "src", "paths": { "@/*": [ "*" ] } }
最后重新启动就能通过 @ 引入文件里
import { login } from '@/api/login'