create-react-app项目,使用自定义别名方案二:craco
发布于 作者:苏南大叔 来源:程序如此灵动~

目的依然是实现在react
项目中实现类似vue
的@
符号功能,除了释放create-react-app
的项目配置外,还可以选择craco
这款第三方库,通过对create-react-app
的简单修改,就可以实现@
别名的需求。本文是系列文章的方案二,使用@craco/craco
来实现这个需求。
苏南大叔的“程序如此灵动”博客,记录苏南大叔的代码编程经验总结。本文测试环境:nodejs@20.18.0
,create-react-app@5.0.1
,react@19.0.0
,craco@7.1.0
。实现这个别名alias
的方案很多,核心就是如何修改webpack
配置,并生效的问题。本文使用@craco/craco
方案。
安装@craco/craco
执行命令:
create-react-app test
cd test
npm i @craco/craco --save-dev
删除无用文件
cd src
rm -r App.test.js reportWebVitals.js setupTests.js
code index.js
配置文件
craco.config.js
:
const path = require('path');
module.exports = {
webpack: {
alias: {
"@": path.resolve(__dirname, "src"),
// 其它的类似别名
},
},
};
修改package.json文件
主要修改的是scripts
字段,把react-scripts
字样修改为craco
。
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
},
测试配置
做个简单的@
测试,修改参考:
import App from '@/App';
测试成功。
相关文章


