Template -- React

React

版本

  • Node 21.6.0
  • Npm 10.2.4

项目

创建

bash 复制代码
npm init vite 项目名称
  • react
  • js
  • npm i
  • npm run dev

依赖

bash 复制代码
npm i axios                 # 网络
npm i antd --save           # UI
npm i @ant-design/icons
npm i react-router-dom      # 路由

npm i sass -D               # sass
npm i vite-plugin-html -D   # html

环境区分

  • package.json
js 复制代码
"scripts" : {
    "dev": "vite --mode test",
    "dev1": "vite --mode production",
    "build": "vite build --mode test",
    "build1": "vite build --mode production"
}
  • package.json 同级
  • .env.test
text 复制代码
NODE_ENV = "test"
VITE_APP_TITLE = "测试"
VITE_APP_BASE_API = "test"
  • .env.production
text 复制代码
NODE_ENV = "production"
VITE_APP_TITLE = "生产"
VITE_APP_BASE_API = "production"
  • vite.config.js
js 复制代码
import { defineConfig,loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { createHtmlPlugin } from "vite-plugin-html";
import { resolve } from "path";

// https://vitejs.dev/config/
export default defineConfig(({ mode, command }) =>{
  const env = loadEnv(mode, process.cwd(), ""); 
  return {
    plugins: [
      react(),
      createHtmlPlugin({
        inject: {
          data: {
            title: env.VITE_APP_TITLE,
          },
        },
      }),
    ],
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"), // 设置 `@` 指向 `src` 目录
      },
    },
    base: "./", // 设置打包路径
    server: {
      port: 4000, // 设置服务启动端口号
      open: true, // 设置服务启动时是否自动打开浏览器
      cors: true, // 允许跨域
      // 设置代理,根据我们项目实际情况配置
      // proxy: {
      //   '/api': {
      //     target: 'http://xxx.xxx.xxx.xxx:8000',
      //     changeOrigin: true,
      //     secure: false,
      //     rewrite: (path) => path.replace('/api/', '/')
      //   }
      // }
    },
  };
})
  • index.html
html 复制代码
<title><%= title %></title>

axios

  • src/http/index.js
js 复制代码
import axios from "axios";

let service = axios.create({
  // baseURL: "https://cnodejs.org/api/v1", //相同绝对路径
  baseURL:import.meta.env.VITE_APP_BASE_API,
  timeout: 100000, //超过这么多时间,则请求终止
  headers: {
    //请求头携带数据的格式
    "Content-Type": "application/json;charset=UTF-8",
    // "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
  },
});
// 添加请求拦截器(Interceptors)
service.interceptors.request.use(
  function (config) {
    // 发送请求之前做写什么
    let token = localStorage.getItem("token");
    // 如果有
    if (token) {
      // 放在请求头(token跟后端沟通,他需要什么该成什么就可以了)
      config.headers.authorization = token;
    }
    return config;
  },
  function (error) {
    // 请求错误的时候做些什么
    return Promise.reject(error);
  }
);
// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    // 对响应数据做点什么
    return response.data;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

export default service;
  • src/http/api.js
js 复制代码
import request from "./index";

export async function Ceshi(params) {
    return request({
      url: "/topics",
      method: "GET",
      params,
    });
  }
  export async function Ceshi2(data) {
    return request({
      url: "/Storage/GetStorageLack",
      method: "POST",
      data,
    });
  }
  • 使用
js 复制代码
import {useEffect, useRef } from "react";
import { Ceshi } from "@/http/api.js";
function App() {
    const cache = useRef(null);
    useEffect(() => {
        async function fetchData() {
            cache.current = true;
            const response = await Ceshi();
            console.log(response);
        }
        if (!cache.current) {
            fetchData();
        }
    }, []);
    return (
        <>
        </>
    );
}

antd

  • 使用
js 复制代码
import { Button } from "antd";

<>
    <Button type="primary">Button</Button>
</>

sass

scss 复制代码
.ddd{
    .adsspan{
        color: aqua;
    }
}

router

  • main.jsx
js 复制代码
import { HashRouter } from "react-router-dom";
<HashRouter><App></App></HashRouter>
  • App.jsx
js 复制代码
import { useRoutes,useNavigate  } from "react-router-dom";

const navigate = useNavigate()
const GetRoutes = () => {
    const routes = useRoutes([
        {
            path: "/",
            element: <Home></Home>,
        },
        {
            path: "/b",
            element: <B></B>,
            children: [
                {
                    path: "/b/aaaa", // /b 需要加,不加找不到
                    element: <C></C> ,
                },
            ],
        },
        {
            path: "/*",
            exact: true,
            element: <div>后台404</div>,
        },
    ]);
    return routes;
};
<GetRoutes />

<Button type="primary" onClick={()=> navigate('/b/aaaa')}>Button</Button>

// 在b页面中加
<Outlet></Outlet>
相关推荐
GISer_Jing2 天前
滴滴二面(准备二)
前端·javascript·vue·reactjs
会飞的小菠菜5 天前
如何根据Excel数据表生成多个合同、工作证、录取通知书等word文件?
word·excel·模板·数据表·生成文件
三思而后行,慎承诺7 天前
requestIdleCallback 和 MessageChannel
javascript·reactjs
Flyfreelylss9 天前
前端实现解析【导入】数据后调用批量处理接口
前端·reactjs
让我们一起加油好吗21 天前
【C++】模板(进阶)
c++·visualstudio·模板·泛型编程
全球网站建设1 个月前
从结构到交互:HTML5进阶开发全解析——语义化标签、Canvas绘图与表单设计实战
javascript·前端框架·php·reactjs·css3·html5
菜鸟555551 个月前
常用算法思想及模板
算法·dp·模板·分治·竞赛·算法思想
光影少年2 个月前
react18更新哪些东西
前端·学习·reactjs
cxr8282 个月前
Vercel AI SDK 3.0 学习入门指南
前端·人工智能·学习·react.js·typescript·npm·reactjs
光影少年2 个月前
react17更新哪些新特性
前端·reactjs