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 直接用@会报如下错:

相关推荐
JarvanMo1 分钟前
Flutter 中的微服务架构:拆解你的应用
前端
JarvanMo3 分钟前
对我来说,那个框架就是 Flutter。
前端
Mintopia10 分钟前
🧠 自监督学习在 WebAIGC 中的技术突破与应用前景
前端·人工智能·aigc
Mintopia13 分钟前
🧭 传统 Web 开发最好的 AI 助手框架排行榜(2025版)
前端·人工智能·aigc
坚持就完事了23 分钟前
003-HTML之表单
服务器·前端·html
光影少年34 分钟前
React Native第六章
javascript·react native·react.js
晓得迷路了37 分钟前
栗子前端技术周刊第 105 期 - npm 安全性加强、Storybook 10、htmx 4.0 Alpha 1...
前端·javascript·npm
七号练习生.c1 小时前
CSS入门
前端·css·tensorflow
程序员爱钓鱼1 小时前
Python编程实战——Python实用工具与库:Matplotlib数据可视化
前端·后端·python