npm init -y
npm i create-react-app
ps:如果失败的话尝试(1:使用管理员身份执行命令(2:切换镜像重试
- create-react-app 项目文件夹名称 --template typescript
-
- //如果不想用ts --template typescript 可以不加
接下来就是一些配置、路由、网络封装什么的。
npm create vite 项目文件夹名称
选择自己想要的一些框架和配置
npm i @types/node --save-dev
在vite.config.ts 引入path加上下面的代码片段
- import { defineConfig } from 'vite';
- import react from '@vitejs/plugin-react';
- import {resolve} from "path";
- export default defineConfig({
- plugins: [react()],
- resolve:{
- alias:{
- "@":resolve(__dirname,'src')
- }
- }
- })
同时在tsconfig.json 让IDE能识别这个别名
- "compilerOptions": {
- "paths": {
- "@/*":["./src/*"]
- }
- },
npm install less
然后在vite.config.ts中进行相关配置
-
- export default defineConfig({
- plugins: [react()],
- resolve: {
- alias: {
- '@': resolve(__dirname,'src')
- }
- },
- css: {
- preprocessorOptions: {
- less: {
- javascriptEnabled: true,
- }
- }
- }
.env.development
和 .env.production
文件,分别用于开发环境和生产环境的配置。- // .env.development
-
- VITE_API_URL=http://localhost:3000/api
- // .env.production
-
- VITE_API_URL=https://example.com/api
const apiUrl = import.meta.env.VITE_API_URL as string;
- {
- "scripts": {
- "dev": "vite --mode development",
- "build": "vite --mode production"
- }
- }
npm i react-router-dom@6
然后在router文件夹下创建index.tsx文件
/src/router/index.tsx
- import type { RouteObject,} from 'react-router-dom';
- import { Navigate } from "react-router-dom";
- import { lazy } from 'react';
-
- const Home = lazy(() => import('@/pages/Home'));
- const NotFound = lazy(() => import('@/pages/NotFound'));//使用路由懒加载优化提升
-
- const routes: RouteObject[] = [
- {
- path: "/",
- element: <Navigate to="/home" />,
- },
- {
- path: '/404',
- element: <NotFound />,
- },
- {
- path: '/home',
- element: <Home />,
-
- // children: [
- // {
- // index : true,
- // element:
- // },
- // {
- // path: "/about",
- // element:
, - // children: [
- // { index : true, element:
}, - // { path : "/about/:id", element :
} - // ]
- // },
- // {
- // path: "/bussiness",
- // element:
, - // }
- // ]
- },
- ];
-
- export default routes;
-
- import React from 'react';
- import './App.css';
- import { useRoutes } from 'react-router';
- import routes from './route';
-
- function App() {
- return (
- <div className="App">
- {useRoutes(routes)}
- div>
- );
- }
-
- export default App;
- import React from 'react';
- import ReactDOM from 'react-dom/client';
- import App from './App';
- import './index.css';
- import { BrowserRouter } from 'react-router-dom';
- ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
- <React.StrictMode>
- <BrowserRouter>
- <App />
- BrowserRouter>
- React.StrictMode>
- );
npm install axios @types/axios
- import axios from 'axios';
- import {baseInfo} from "../common/config";
- import {getToken,removeToken,} from "../common/storage";
- export function requestAdmin(config){
- let Token = getToken();
- if(Token){
- config.headers={
- ...config.headers,
- 'Token' : `${Token}`,
- 'Authorization' : `token`,
- }
- }
-
- const instance = axios.create({
- baseURL:"",
- headers:{...config.headers},
- timeout:100000
- });
- // axios请求拦截器 请求
- instance.interceptors.request.use(config=>{return config;},err=>{console.log(err);})
- // axios响应拦截器 数据返回
- instance.interceptors.response.use(res=>{
- let {code,message} = res.data;
- //判断用户登录的token是否过期做某些操作
- if(code === ...){
-
- }
-
- return res;
- },err=>{
- console.log(err);
- })
- return instance(config);
- }
- //引用axios封装函数
- import {requestAdmin} from "@/network/request";
-
- /**
- * 登录
- * @param data
- */
- export function doLogin(data:any){
- return requestAdmin({
- url:"",
- data,
- method:"post"
- })
- }
(3 使用
- //引入network的网络请求接口
- import { requestLogin } from "@/network/v1/login/index"
- interface InitProps{}
- const Login:FC<InitProps> = (props:InitProps)=>{
- const onLogin = (values: any) => {
- let data = {};
- requestLogin(data).then((res: resInterface) => {
- let { code, data,message } = res.data;
- if (code === 200) {
- showSuccess('登录成功');
- setToken(data.token);
- setTimeout(_ =>{
- setLoading(false)
- },1000)
- } else {
- showError(`${message}`);
- setLoading(false)
- }
- }).catch((err:any) => {
- console.log(err);
- })
- };
- return (
- <React.Fragment>
- <Button onClick={onLogin}>去登录Button>
- React.Fragment>
- )
- }
-
- export default Login;
这里可以自行选择适合自己的框架类似于antd、Material UI...等
这里我选的是移动端Material UI 官方文档 Installation - Material UI
npm install @mui/material @emotion/react @emotion/styled
- import { useState } from 'react';
- import { Button } from '@mui/material';
-
- import Container from '@mui/material/Container';
- import { styled } from '@mui/material/styles';
- import Box from '@mui/material/Box';
- import Paper from '@mui/material/Paper';
- import Grid from '@mui/material/Grid';
-
- function Home() {
- const [count, setCount] = useState(0);
-
- const Item = styled(Paper)(({ theme }) => ({
- backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
- ...theme.typography.body2,
- padding: theme.spacing(1),
- textAlign: 'center',
- color: theme.palette.text.secondary,
- }));
-
- return (
- <Container fixed>
- <Box sx={{ flexGrow: 1 }}>
- <Grid container spacing={2}>
- <Grid item xs={12}>
- <Item>banner区域Item>
- Grid>
- <Grid item xs={12}>
- <Item>广告区域Item>
- Grid>
- <Grid item xs={4}>
- <Item>xs=4Item>
- Grid>
- <Grid item xs={8}>
- <Item>xs=8Item>
- Grid>
- Grid>
- Box>
- Container>
- );
- }
-
- export default Home;
以上就是所有内容,感谢阅读。