小工具知识网

当前位置: 首页 > 行业知识 > react 使用 craco库 配置 @ 路径,以及 jsconfig.json或者tsconfig.json 配置智能提示

行业知识

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

2026-10-30 02:06:17 来源:互联网转载

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

上一篇:怎么设立个人网站?

下一篇:DDBO软件资源下载宝典,轻松获取优质软件,一键开启你的使用之旅!