
【vite4+react18+react-router6+ts+scss+项目配置】一、安装环节
在tsconfig.json和tsconfig.app.json配置ts对别名的支持。在src目录下新建router文件夹,在其内新建index.tsx文件,设计路由表。创建index.module.scss。vite.config.ts文件。1.初始化react项目。
·
1.初始化react项目npm init vite@latest
2.配置别名和端口号:
pnpm install @types/node
vite.config.ts文件
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
port:3000,//端口号
open:'/',//开始运行时自动打开的页面
},
resolve: {
// 配置别名
alias: {
"@": path.resolve(__dirname, "src"),
},
},
});
在tsconfig.json和tsconfig.app.json配置ts对别名的支持
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
3.配置路由
在src目录下新建router文件夹,在其内新建index.tsx文件,设计路由表
pnpm install react-router-dom @types/react-router-dom
import { lazy } from "react";
import { Navigate, useRoutes } from "react-router-dom";
const Home = lazy(() => import("@/pages/home/index"));
const User = lazy(() => import("@/pages/user/index"));
const ManageUser = lazy(() => import("@/pages/user/manageUser"));
const UpdatePassword = lazy(() => import("@/pages/user/updatePassword"));
const NotFound = lazy(() => import("@/pages/error/notFound"));
const routes = [
//配置/重定向路由
{
path: "/",
element: <Navigate to="/home" replace />,
},
{
path: "/home",
element: <Home />,
},
{
path: "/user",
element: <User />,
//嵌套路由
children: [
{
path: "/user/manageUser",
element: <ManageUser />,
},
{
path: "/user/updatePassword",
element: <UpdatePassword />,
},
//配置默认的重定向路由
{
path: "",
element: <Navigate to="/user/manageUser" replace />,
},
],
},
// 匹配不到的路由都展示404页面
{
path: "*",
element: <NotFound />,
},
];
function Router() {
return useRoutes(routes);
}
export default Router;
页面:
function Home() {
return (
<>
首页
</>
);
}
export default Home;
4.配置scss
pnpm install sass sass-loader -D
创建index.module.scss
.title {
font-size: 20px;
.link {
color: aqua;
}
}
.link {
color: rgb(131, 197, 76);
}
在文件中使用:
import selfStyle from "./index.module.scss";
function Home() {
return (
<>
<div className={selfStyle.title}>
{/* 这里的.link会优先匹配.title下的.link */}
我是<span className={selfStyle.link}>首页</span>
</div>
</>
);
}
export default Home;
更多推荐
所有评论(0)