【React+Ts+Vite+AntDesign】从0到1基础项目搭建(动态路由)

新建项目

javascript 复制代码
npm create vite




配置路由

项目根目录执行命令安装依赖

javascript 复制代码
npm install react-router-dom

安装AntDesign

项目根目录执行命令安装依赖

javascript 复制代码
npm install antd --save

至于使用AntDesign,就这一步就可以了,使用table举例:

官网:https://ant.design/components/table-cn

其他关键配置

src>新建router文件夹>新建index.tsx

javascript 复制代码
// index.tsx
import { lazy, ComponentType } from 'react'

// 动态路由部分
const pages = import.meta.glob('../pages/**/*.tsx')
const dynamicRoutes = Object.entries(pages)
  .filter(([path]) => !path.includes('/components/'))
  .map(([path, component]) => {
    const name = path.match(/\.\.\/pages\/(.*)\.tsx$/)?.[1]
    if (!name) return null
    let routePath = `/${name.toLowerCase()}`
    routePath = routePath.replace(/\/index$/, '').replace(/\[([^\]]+)\]/g, ':$1')
    if (routePath === '/index') routePath = '/'
    return {
      path: routePath,
      element: lazy(component as () => Promise<{ default: ComponentType<any> }>)
    }
  })
  .filter(Boolean)

// 固定路由部分
const notView = lazy(() => import('../404'))
const Home = lazy(() => import('@/pages/Home/index'))
const staticRoutes = [
  {
    path: '/',
    element: Home
  },
  {
    path: '*',
    element: notView 
  }
]
// 合并动态路由和固定路由
const routes = [...staticRoutes, ...dynamicRoutes]
export default routes

App.tsx

js 复制代码
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import routes from './router'
import { Suspense } from 'react'

function App() {
  const safeRoutes = routes || []
  return (
    <BrowserRouter>
      <div>
        <Suspense fallback={<div>Loading...</div>}>
          <Routes>
            {safeRoutes.map(
              (route) =>
                route && <Route key={route.path} path={route.path} element={<route.element />} />
            )}
          </Routes>
        </Suspense>
      </div>
    </BrowserRouter>
  )
}
export default App

src>新建pages文件夹

再新建Home文件夹>index.tsx

js 复制代码
// src/pages/Home/index.tsx
import React from 'react';

const Home: React.FC = () => {
  return <div>Home Page</div>;
};

export default Home;

测试页面,能正常显示内容就ok。

后续所有跳转页面都在pages/目录

例:

这样就不用一个一个傻瓜式的写路由了,只需要管理文件,路由自动读取。

关于出现问题:

报错找不到模块"@/

修改vite.config.ts

js 复制代码
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
import { resolve } from 'path'

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': resolve('./src'),
    },
  },
});

修改tsconfig.json

js 复制代码
{
  "compilerOptions": {
    "baseUrl": "./", // 设置基础路径为当前目录
    "paths": { // 配置路径映射,@ 符号代表 src 目录
      "@/*": ["./src/*"]
    },
    "target": "ES2020", // 目标编译版本为 ES2020
    "useDefineForClassFields": true, // 允许类字段使用 defineProperty 进行定义
    "module": "ESNext", // 使用 ES 模块系统
    "lib": ["ES2020", "DOM", "DOM.Iterable"], // 编译时需要引入的库
    "skipLibCheck": true, // 跳过库文件的类型检查

    /* Bundler mode */
    "moduleResolution": "bundler", // 模块解析策略为 bundler
    "allowImportingTsExtensions": true, // 允许导入 TypeScript 扩展文件
    "resolveJsonModule": true, // 允许导入 JSON 模块
    "isolatedModules": true, // 确保每个文件都可以单独编译
    "noEmit": true, // 不生成输出文件
    "jsx": "preserve", // 保留 JSX 语法

    /* Linting */
    "strict": true, // 启用所有严格类型检查选项
    "noUnusedLocals": true, // 禁止未使用的局部变量
    "noUnusedParameters": true, // 禁止未使用的函数参数
    "noFallthroughCasesInSwitch": true // 禁止 switch 语句中存在空缺情况
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"] // 包含的文件类型
}

报错__dirname波浪线

执行代码

js 复制代码
npm install @types/node --save-dev

感谢你的阅读,如对你有帮助请收藏+关注!

只分享干货实战精品从不啰嗦!!!

如某处不对请留言评论,欢迎指正~

博主可收徒、常玩QQ飞车,可一起来玩玩鸭~

相关推荐
蓝婴天使21 分钟前
基于 React + Go + PostgreSQL + Redis 的管理系统开发框架
react.js·postgresql·golang
鸠摩智首席音效师27 分钟前
如何清除 Yarn 缓存 ?
javascript
oh,huoyuyan1 小时前
如何在火语言中指定启动 Chrome 特定用户配置文件
前端·javascript·chrome
前端大聪明20021 小时前
single-spa原理解析
前端·javascript
一枚前端小能手1 小时前
📦 从npm到yarn到pnpm的演进之路 - 包管理器实现原理深度解析
前端·javascript·npm
@大迁世界2 小时前
Promise.all 与 Promise.allSettled:一次取数的小差别,救了我的接口
开发语言·前端·javascript·ecmascript
知识分享小能手2 小时前
微信小程序入门学习教程,从入门到精通,项目实战:美妆商城小程序 —— 知识点详解与案例代码 (18)
前端·学习·react.js·微信小程序·小程序·vue·前端技术
DoraBigHead2 小时前
React 中的代数效应:从概念到 Fiber 架构的落地
前端·javascript·react.js
今天头发还在吗3 小时前
【框架演进】Vue与React的跨越性变革:从Vue2到Vue3,从Class到Hooks
javascript·vue.js·react.js
渣哥3 小时前
从 AOP 到代理:Spring 事务注解是如何生效的?
前端·javascript·面试