【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飞车,可一起来玩玩鸭~

相关推荐
多加点辣也没关系2 小时前
JavaScript|第9章:对象 — 基础
开发语言·javascript·ecmascript
后台开发者Ethan3 小时前
setState组件更新
前端·javascript·react
蜡台4 小时前
uniapp vue2 转 vue3
前端·javascript·uni-app·vue3·vue2
WindfallSheng4 小时前
从Vibe Coding到Spec Coding:一套可落地的AI-SDD企业级研发实战工程
javascript·vue.js
Asize5 小时前
Agent 入门:从 LLM 与 Agent 的区别到 Function Calling
javascript·人工智能
我有满天星辰5 小时前
Vue 指令完全指南:从 Vue 2 到 Vue 3 的演进与实战
前端·javascript·vue.js
光影少年5 小时前
RN 渲染原理:不依赖WebView,原生控件渲染
前端·react native·react.js·前端框架
小白学过的代码5 小时前
# flv.js / mpegts.js 播不了国标摄像头(H.265 + G.711A)?纯前端 Jessibuca 无后端方案(附完整代码)
前端·javascript·h.265
我有满天星辰8 小时前
Vue 3 响应式双雄:ref 与 reactive 完全指南
前端·javascript·vue.js
随风一样自由16 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery