vite+react+ts+mobx+antd+react-router-dom+sass+tailwindcss

I have written a lot of Vue projects. Recently, I want to change the react technology stack and exercise my skills. Without further ado, let’s start creating projects. This blog is just to record the process of my creation. Unable versions will inevitably have pitfalls. Welcome to share and discuss!

1. npm create vite // Use vite to create a project, the picture below is the configuration of the created selection, you can refer to the following

 After creating it, cd into the corresponding folder, open the vscode software with the command code ., and then install the dependencies. This step is very simple. pnpm i can be installed directly

After installing the dependencies, the project will run normally. Next is the configuration directory file. You can refer to my project directory. This directory is all customized and depends on your own programming habits. There is no fixed one. Standard, because I basically work alone on the company's projects.

 2. Install the antd UI component (the default installation is the latest version of antd UI)

pnpm i antd -S

My projects all use pnpm to install plug-ins and dependencies. I think pnpm is easier to use, and the installed image is still relatively small.

3. After the installation is complete, it is time to introduce the css of the UI

It can be introduced directly in the entry file main.tsx

import 'antd/dist/reset.css';

4. You can also create a style folder in the src directory, put an index.css file in it, and write

@import 'antd/dist/reset.css';

The effect of both is the same, but the way of introduction is different. Pay attention, there is still a difference. The @ symbol must be added to the css.

After the installation is complete, try it in App.tsx, and it is basically successful.

Note that my installation method is to import all, not to load on demand

 5. Configure the project path and running port number in vite.config.ts

// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path, { resolve } from "path";

export default defineConfig({
  server: {
    host: "0.0.0.0", //解决 vite use--host to expose
    port: 8888, //配置端口
    open: true, //配置默认打开浏览器
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"), //配置@别名
    },
  },
  plugins: [react()],
});

You also need to configure the path in tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "./",  // 这个重要
    "paths": { //  // 这个重要
      "@/*": ["src/*"]
    }
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Restart the project and refresh the configuration. In fact, @/ means starting from src and finding the folder of the corresponding directory. 

 6. Install the react-router-dom v6 version of routing

pnpm i react-router-dom -S // 默认安装就是最新的版本的

Use routing in main.tsx, which is applied to the entire app

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { Provider } from "mobx-react";
import App from "./App";
import "@/style/index.css";
import store from "./store/index";

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <BrowserRouter> // 使用历史模式,
      <Provider store={store}> // 这个是仓库,mobx,晚点会讲
        <App />
      </Provider>
    </BrowserRouter>
  </React.StrictMode>
);

 Then create a new router folder and put the corresponding routing file in it. I wrote it by imitating Vue's routing.

 My writing method is to refer to the boss's writing method, put all the sub-routes in modules, load them all through import.meta.globEager(./modules/*.tsx), and after loading them back, process the data format by myself. It also includes routing login interception, all written in the code.

// index.tsx

import { Navigate, Route, RouteProps } from "react-router-dom";
import BasicLayout from "@/layouts/BasicLayout/BasicLayout";
import SignIn from "@/pages/login";
import cookies from "js-cookie";
import {
  ReactElement,
  JSXElementConstructor,
  ReactFragment,
  ReactPortal,
} from "react";

const modules = import.meta.globEager("./modules/*.tsx");

let routerModuleList: any[] = [];

Object.keys(modules).forEach((key) => {
  const mod = modules[key].default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routerModuleList.push(...modList);
});

// 升序排序
routerModuleList = routerModuleList.sort((a, b) => {
  // a-b 小于0 升序,大于零,是降序
  return (a.sort || 99) - (b.sort || 100);
});

const routes: any = [
  {
    path: "/",
    element: <Navigate to={"/layout/homePage"} />,
  },
  {
    path: "/layout",
    element: <VerifyLogin element={<BasicLayout />} />,
    children: [],
  },
  {
    path: "/login",
    element: <login/>,
  },
];

// 实现路由拦截
function VerifyLogin(prop: { element: ReactElement }) {
  const isLogin = cookies.get("token");
  return isLogin ? prop.element : <Navigate to="/login" replace />;
}

routes[1].children = routerModuleList;

export default routes;

Then the sub-routing specification

The specific code method of the sub-routing 

import { Navigate, Outlet } from "react-router-dom";
import Home from "@/pages/home/index";

const routes = [
  {
    sort: 1,
    path: "/layout/homePage",
    element: <Outlet />,
    meta: {
      title: "首页",
    },

    children: [
      {
        path: "/layout/homePage/homeDetail",
        element: <Home />,
        meta: {
          title: "首页详情",
        },
      },
    ],
  },
];

export default routes;

7. Install sass 

 npm install --save-dev sass

I used it directly and did not need to install sass-loader for compilation. I am quite weird. I basically imported the index.scss directly into the corresponding file on each page. There was no problem of style pollution. If yours Now, you can use this index.module.scss. It uses the module keyword to isolate styles. You don’t need to configure anything to install sass. You can just use it directly.

 8. Configure variables for multiple environments. By changing the package.json file, use --mode to specify the running configuration of different environments. This is what I do.

 

Create different corresponding environment files in this root directory. Of course, we will use them in the project later.

In this way, you can also agree to log and take a look at it. It is very simple.


const { VITE_BASE_URL, VITE_NODE_ENV } = import.meta.env;

 9. Install mobx

pnpm i mobx mobx-react -S

I originally used redux, but it took me a long time to fix it, but it was not done well. The project is not very big, so mobx is enough.

Specific usage

in index.ts

import MenuStore from "./menu";
class Store {
  menuStore: MenuStore;

  constructor() {
    this.menuStore = new MenuStore();
  }
}

export default new Store();

 menu.ts medium

import { runInAction, makeAutoObservable } from "mobx";

// 对初始化数据进行响应式处理 mobx v6不支持装饰器写法
export default class MenuStore {
  constructor() {
    makeAutoObservable(this);
  }

  // 导航
  breadcrumbData = [];
  // 处理面包屑导航
  currentPath(path: string) {
    this.breadcrumbData = treeFindPath(
      routes[1].children,
      (data) => data.path === path,
      "meta"
    );

// 发起请求
 async fetchProjects() {
        try {
            const projects = await fetchGithubProjectsSomehow()
            // await 之后,再次修改状态需要动作:
            runInAction(() => {
                this.githubProjects = filteredProjects
            })
        } catch (error) {
            runInAction(() => {
                this.state = "error"
            })
        }
    }


  //销毁组件时重置参数
  reset() {}
}

10. Then install tailwindcss

pnpm i tailwindcss@latest postcss@latest autoprefixer@latest

After the installation is successful, you still need to configure it. Execute the command

npx tailwindcss init will generate two files in the root directory. If not, you can create them yourself.

They must be tailwind.config.cjs and postcss.config.cjs respectively. The suffix must be cjs. Pay attention.

tailwind.config.cjs file configuration

module.exports = {
  purge: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

postcss.config.cjs file configuration

const tailwindcss = require("tailwindcss");

module.exports = {
  plugins: [tailwindcss("./tailwind.config.cjs"), require("autoprefixer")],
};

Once created, the style of tailwindcss is referenced. You can directly introduce the style file into App.tsx in the startup file, or you can create a general style file yourself to uniformly introduce the style file.

 Create tailwind.css file

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

My file directory structure

11. Install reset to reset the browser’s reset style.

pnpm install --save normalize.css

Introduce it in the overall style file, and finally import it into the entry file, which is main.tsx

@import 'antd/dist/reset.css';

@import './normal.scss';

import 'normalize.css/normalize.css' // 这个是安装的重置样式

@import './tailwind.css'

12. Configure the address for vite+reatc to run and run after packaging.

// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path, { resolve } from "path";

export default defineConfig({
  base: "/test", // 配置运行的地址
  server: {
    host: "0.0.0.0", //解决 vite use--host to expose
    port: 8888, //配置端口
    open: true, //配置默认打开浏览器
  },
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"), //配置@别名
    },
  },
  plugins: [react()],
});

Vite document address 

 

Guess you like

Origin blog.csdn.net/zq18877149886/article/details/130331052