Template -- React

React

版本

  • Node 21.6.0
  • Npm 10.2.4

项目

创建

npm init vite 项目名称
  • react
  • js
  • npm i
  • npm run dev

依赖

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
"scripts" : {
    "dev": "vite --mode test",
    "dev1": "vite --mode production",
    "build": "vite build --mode test",
    "build1": "vite build --mode production"
}
  • package.json 同级
  • .env.test
NODE_ENV = "test"
VITE_APP_TITLE = "测试"
VITE_APP_BASE_API = "test"
  • .env.production
NODE_ENV = "production"
VITE_APP_TITLE = "生产"
VITE_APP_BASE_API = "production"
  • vite.config.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
<title><%= title %>title>

axios

  • src/http/index.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
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,
    });
  }

  • 使用
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

  • 使用
import { Button } from "antd";

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

sass

.ddd{
    .adsspan{
        color: aqua;
    }
}

router

  • main.jsx
import { HashRouter } from "react-router-dom";
<HashRouter><App></App></HashRouter>
  • App.jsx
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>

你可能感兴趣的:(reservoir,reactjs,模板)