能够让vscode识别@路径并给出路径提示
步骤
- 在项目根目录创建
jsconfig.json配置文件 - 在配置文件中添加以下配置
jsconfig.json 中:
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"]
}
}
}
小结
VSCode 会自动读取 jsconfig.json 中的配置,让 vscode 知道 @ 就是 src 目录
用craco来配置路径别名
目标
配置@路径别名,让脚手架工具能识别@
背景
CRA(create-react-app) 将所有工程化配置,都隐藏在了 react-scripts 包中,所以,项目中看不到任何配置信息或者是配置文件。
如果要修改 CRA 的默认配置,有以下几种方案:
- 【推荐】通过第三方库来修改,比如,
@craco/craco - 通过执行
yarn eject命令,释放react-scripts中的所有配置到项目中(注意:该操作不可逆!!!)
craco是什么
Create React App Configuration Override, an easy and comprehensible configuration layer for create-react-app
craco是用来对create-react-app进行自定义配置的工具。
craco的使用步骤
-
安装包。
npm i -D @craco/craco -
在项目根目录下,创建配置文件:
craco.config.js。在配置文件中就可以做自定义的修改了。craco.config.js
配置路径别名
const path = require('path') module.exports = { webpack: { alias: { '@': path.join(__dirname, 'src') } } } -
修改
package.json中的脚本命令package.json 中:
// 将 start/build/test 三个命令修改为 craco 方式 "scripts": { "start": "craco start", "build": "craco build", "test": "craco test", "eject": "react-scripts eject" }, -
在代码中,就可以通过
@来表示 src 目录的绝对路径 -
重启项目,让配置生效