react 使用 craco库 配置 @ 路径,以及 jsconfig.json或者tsconfig.json 配置智能提示

使用 craco库 来自定义CRA配置

1、概述

Craco(Create React App Configuration Override)是一个用于扩展 Create React App(CRA)配置的工具。通过 Craco,你可以在不弹出 Create React App 的内部配置的情况下,轻松地对 CRA 的配置进行自定义。
craco配置文档:https://github.com/dilanx/craco/blob/main/packages/craco/README.md#configuration

2、安装craco

复制代码
npm i -D @craco/craco

3、在项目 根目录中创建 craco 的配置文件:craco.config.js,并在配置文件中配置路径别名,代码如下:

复制代码
const path = require('path')

module.exports = {
  // webpack 配置
  webpack: {
    // 配置别名
    alias: {
      // 约定:使用 @ 表示 src 文件所在路径
      '@': path.resolve(__dirname, 'src')
    }
  }
}

4、修改 package.json 中的脚本命令

packge.json 文件中将以下代码

复制代码
"scripts": {
    "start": "react-scripts start"
    "build": "react-scripts build"
    "test": "react-scripts test"
    "eject": "react-scripts eject"
}

修改成:

复制代码
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },

5、配置vscode识别@路径并给出路径提示

在项目根目录创建 jsconfig.json 或者 tsconfig.json 配置文件,代码如下:

复制代码
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

注意: 如果是 TS 没有先配置 tsconfig.json 直接用@会报如下错:

相关推荐
蓝倾13 分钟前
淘宝批量获取商品SKU实战案例
前端·后端·api
comelong17 分钟前
Docker容器启动postgres端口映射失败问题
前端
花海如潮淹19 分钟前
硬件产品研发管理工具实战指南
前端·python
用户38022585982420 分钟前
vue3源码解析:依赖收集
前端·vue.js
WaiterL20 分钟前
一文读懂 MCP 与 Agent
前端·人工智能·cursor
gzzeason23 分钟前
使用Vite创建React初始化项目
前端·javascript·react.js
又双叒叕77823 分钟前
React19 新增Hooks:useOptimistic
前端·javascript·react.js
归于尽42 分钟前
V8 引擎是如何给 JS"打扫房间"的 ?
前端·javascript
小old弟43 分钟前
让对象保持定义的顺序来排列
前端
漫天星梦43 分钟前
前端列表页大数据内存优化的思考
前端·面试