React
版本
项目
创建
npm init vite 项目名称
依赖
npm i axios
npm i antd --save
npm i @ant-design/icons
npm i react-router-dom
npm i sass -D
npm i vite-plugin-html -D
环境区分
"scripts" : {
"dev": "vite --mode test",
"dev1": "vite --mode production",
"build": "vite build --mode test",
"build1": "vite build --mode production"
}
NODE_ENV = "test"
VITE_APP_TITLE = "测试"
VITE_APP_BASE_API = "test"
NODE_ENV = "production"
VITE_APP_TITLE = "生产"
VITE_APP_BASE_API = "production"
import { defineConfig,loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { createHtmlPlugin } from "vite-plugin-html";
import { resolve } from "path";
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"),
},
},
base: "./",
server: {
port: 4000,
open: true,
cors: true,
},
};
})
<title><%= title %></title>
axios
import axios from "axios";
let service = axios.create({
baseURL:import.meta.env.VITE_APP_BASE_API,
timeout: 100000,
headers: {
"Content-Type": "application/json;charset=UTF-8",
},
});
service.interceptors.request.use(
function (config) {
let token = localStorage.getItem("token");
if (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;
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
import { HashRouter } from "react-router-dom";
<HashRouter><App></App></HashRouter>
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",
element: <C></C> ,
},
],
},
{
path: "/*",
exact: true,
element: <div>后台404</div>,
},
]);
return routes;
};
<GetRoutes />
<Button type="primary" onClick={()=> navigate('/b/aaaa')}>Button</Button>
<Outlet></Outlet>