首页 > 其他分享 >ReactJS单页面应用之项目搭建

ReactJS单页面应用之项目搭建

时间:2022-10-27 00:55:38浏览次数:108  
标签:sysmgmt App ReactJS react router import 页面 app 搭建

初衷

因接手的项目前端采用reactjs+antd,为把控项目中的各个细节,所以想做一些整理,以免后期遗忘。

创建及启动项目

# 全局安装create-react-app 
# 如果曾经安装过,可先移除: npm uninstall -g create-react-app
npm install -g create-react-app

# 创建项目sysmgmt
npx create-react-app sysmgmt --template typescript

# 进入项目目录
cd sysmgmt

# 启动
npm start

为项目增加路由功能

安装依赖

# 安装react-router-dom
npm install --save react-router-dom @types/react @types/react-dom @types/react-router

添加及修改相关文件

@/src/routes/index.tsx

import { lazy, LazyExoticComponent } from 'react';

export type RouterType = {
   path: string,
   component: LazyExoticComponent<() => JSX.Element>,
 }[]
 
 const Routers: RouterType = [{
   path: 'home',
   component: lazy(() => import ('../pages/Home'))
 },{
   path: 'details',
   component: lazy(() => import ('../pages/Details'))
 },]
 
 export default Routers

@/src/App.tsx

import React, { Suspense } from 'react'
import './App.css';
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
import Routers from './routes';
import Loading from './components/Loading';
import BasicLayout from './layout/BasicLayout';

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<Loading />}>
        <Routes>
          <Route path='/' element={<BasicLayout />}>
            {
              Routers.map(router => {
                return (
                  <Route
                    key={router.path}
                    path={router.path}
                    element={<router.component />}
                  >
                </Route>
                )
              })
            }
            <Route path='' element={<Navigate to={'home'}/>}/>
          </Route>
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

export default App;

项目源码

sysmgmt

参考资料

https://www.jianshu.com/p/727d836d1d47
https://cloud.tencent.com/developer/article/1842697
https://cloud.tencent.com/developer/article/2098078

标签:sysmgmt,App,ReactJS,react,router,import,页面,app,搭建
From: https://www.cnblogs.com/bsmn/p/16830673.html

相关文章