React项目配置路径别名“@”

React项目配置路径别名"@"

首先安装craco

bash 复制代码
npm i @craco/craco@alpha -D
npm i npm i craco-less

创建craco.config.js

bash 复制代码
const path = require('path')
const CracoLessPlugin = require('craco-less')

const resolve = (dir) => path.resolve(__dirname, dir)

module.exports = {
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            // modifyVars: { '@primary-color': '#1DA57A' },
            javascriptEnabled: true
          }
        }
      }
    }
  ],
  webpack: {
    alias: {
      '@': resolve('src'),
      components: resolve('src/components')
    }
  }
}

修改tsconfig.json

bash 复制代码
{
  "compilerOptions": {
    .......加上如下两个配置(删掉这个)
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"]
    }
  },
  "include": [
    "src"
  ]
}

修改package.json 使用craco启动项目

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

最后启动成功后可能会出现问题 提示你 babel-preset-react-app 未在其依赖中声明

你需要继续安装

bash 复制代码
npm install --save-dev @babel/plugin-proposal-private-property-in-object
相关推荐
陈随易7 小时前
Postman 被曝自动往 Claude Code 和 Codex 装插件
前端·后端·程序员
Csvn10 小时前
性能监控
前端
Csvn11 小时前
构建工具
前端
FRing0311 小时前
vue2干货总结3(computed计算属性、watch监听器)
开发语言·前端·vue.js·vue2
JavaPub-rodert12 小时前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
kyriewen13 小时前
Skills 榜前 10 我全装了:只有 3 个能直接用
前端·javascript·程序员
IT_陈寒14 小时前
当Java的hashCode遇上Lombok,我的缓存被全清了
前端·人工智能·后端
工控丫丫14 小时前
帆软看板中经常使用的公式函数及经常搭的组合
前端·javascript·数据库
jerrywus14 小时前
我用 GPT-6.1-sol 做了台会讲解的 3D 售货机:60 罐饮料,一口没喝上
前端·agent·claude
孟陬16 小时前
Foobar 技术周刊#159:当看不懂代码时,如何高效排障调试。脏页陷阱:一条只读查询,写入数 TB 数据。推测解码:大模型加速利器
前端·人工智能·后端