preface

Daily flying pigeons, tongs Liu Ming

This is a React project based on Vite, and the development experience is great.

Create a Vite project

yarn create @vitejs/app
Copy the code

Select the React-TS default template as shown in the image above

yarn          // Install dependencies
yarn dev      // Start the development environment
Copy the code

Open your browser and type http://localhost:3000/#/, as shown in the image above. Congratulations, you can now work on the React project. End and spend

If not, go directly to the Vite website, which is more detailed than I wrote


The reconstruction project

However, the above is only a basic React demo. In actual development projects, it is far from enough. Some additional project configurations are required

Directory conventions

Start with basic directory conventions based on daily development practices

├ ─ ─ dist /// Default build output directory└ ─ ─ SRC /// Source directory├ ─ ─ assets /// Static resource directory├ ─ ─ the config ├ ─ ─ config. Js// Basic configurations related to internal services of the project├ ─ ─ the components /// Public component directory├ ─ ─ service /// Business request management├ ─ ─ store /// Share store management directory├ ─ ─ until /// Directory of utility functions├ ─ ─ pages /// Page directory├ ─ ─ the router /// Route configuration directory├ ─ ─. Main. TSX// Vite relies on the main entry├ ─ ─ the env// Environment variable configuration├ ─ ─ vite. Config. Ts// Vite configuration selection, specific can see the official website API└ ─ ─ package. JsonCopy the code

Configure the routing

Reforming the main benchmark

import React from 'react'
import ReactDOM from 'react-dom'
import { HashRouter, Route, Switch } from 'react-router-dom'
import routerConfig from './router/index'
import './base.less'

ReactDOM.render(
  <React.StrictMode>
    <HashRouter>
      <Switch>
        {
          routerConfig.routes.map((route) => {
            return (
              <Route key={route.path} {. route} / >)})}</Switch>
    </HashRouter>
  </React.StrictMode>.document.getElementById('root'))Copy the code

The router/index.ts file was configured

import BlogsList from '@/pages/blogs/index'
import BlogsDetail from '@/pages/blogs/detail'

export default {
  routes: [{exact: true.path: '/'.component: BlogsList },
    { exact: true.path: '/blogs/detail/:article_id'.component: BlogsDetail },
  ],
}
Copy the code

You can refer to the above configuration to configure other common route configuration items, such as redirect and lazy loading

In addition, individuals tend to generate routing through configuration, which is not very convenient.

The service management

All project requests are put into service, and it is recommended that each module have corresponding file management, as shown below

import * as information from './information'
import * as base from './base'

export {
  information,
  base
}
Copy the code

This facilitates request management

Base.ts, as a business request class, can handle some business special processing here

import { request } from '.. /until/request'

const prefix = '/api'

export const getAllInfoGzip = () = > {
  return request({
    url: `${prefix}/apis/random`.method: 'GET'})}Copy the code

As a unified request method, until/ Request can be customized to replace fetch, AXIOS and other request libraries, and can encapsulate the common interception logic in this method.

import qs from 'qs'
import axios from "axios";

interface IRequest {
    url: stringparams? : SVGForeignObjectElement query? :objectheader? :objectmethod? :"POST" | "OPTIONS" | "GET" | "HEAD" | "PUT" | "DELETE" | undefined
}

interface IResponse {
    count: number
    errorMsg: string
    classify: string
    data: anydetail? :anyimg? :object
}

export const request = ({ url, params, query, header, method = 'POST' }: IRequest): Promise<IResponse> => {
    return new Promise((resolve, reject) = > {
        axios(query ? `${url}/?${qs.stringify(query)}` : url, {
            data: params,
            headers: header,
            method: method,
        })
            .then(res= > {
                resolve(res.data)
            })
            .catch(error= > {
                reject(error)
            })
    })
}
Copy the code

For specific general interception, please refer to axiOS configuration, or you can adapt to your own business requirements.

There is something wrong with the resource built using AXIos, do not copy the code directly to use it, please refer to the previous request encapsulation and replace it with FETCH. If any students copy the code successfully, please leave a message = =!

You can import the interface module based on the module name for service development, so that you can easily find the corresponding interface module

import { information } from "@/service/index";

const { data } = await information.getAllInfoGzip({ id });
Copy the code

This set of rules can also be applied to store, router, utils and other places where modules can be disassembled, which is conducive to project maintenance.

The above is for the project to do some business development configuration and agreement, you can modify according to the rules and preferences of your team.

Other configuration

This is mainly about the configuration of vite. Config. ts, do some additional configuration for the project as a whole.

import { defineConfig } from 'vite'
import reactRefresh from '@vitejs/plugin-react-refresh'
import vitePluginImp from 'vite-plugin-imp'

export default defineConfig({
  plugins: [
    reactRefresh(),
    vitePluginImp({
      libList: [{libName: 'antd-mobile'.style(name) {
            return `antd-mobile/lib/${name}/style/index.css`},},]})],resolve: {
    extensions: ['.mjs'.'.js'.'.ts'.'.jsx'.'.tsx'.'.json'].alias: {
      The '@': '/src'}},server: {
    proxy: {
      // This is an option
      '/api': {
        target: 'https://www.xxx.xxx'.changeOrigin: true.rewrite: (path) = > path.replace(/^\/api/.' ')}}},css: {
    postcss: {
      plugins: [
        require('postcss-pxtorem') ({// Convert px units to REM units
          rootValue: 32.// Set the font size of the root tag to 1rem 50px, so that you can measure the number of px from the design and write more px directly in the code.
          propList: [The '*'].// Property selector, * for general
          unitPrecision: 5.// The number of decimal digits that REM units are allowed to grow to, reserved after the decimal point.
          exclude: /(node_module)/.// By default false, you can (reg) exclude certain folder methods using regular expressions})]}}})Copy the code

There are some basic things:

  • VitePluginImp is antD-Mobile loaded on demand
  • Postcss-pxtorem is a plug-in for configuring mobile PX conversion
  • Server. proxy Configures the project proxy
  • Resolve. Alias Specifies the alias. If vscode is required to identify the alias, ts.config also needs to be configured
{
  "compilerOptions": {
    "baseUrl": ". /"."paths": {
      "@ / *": [
        "src/*"]}}Copy the code

Antd-mobile can be replaced by ANTD, and postCSS can also be replaced according to your preferences

With the above simple transformation, normal small project development can now be carried out. End scatter flower!

A simple H5 project has been written with this configuration, and the template will be refined as the project iterates.

eggs

Since the markdown compatibility of the applet was really a bit poor, this section was rewritten in H5

Markdown parsing is done directly with the byte open source Markdown editor, which is nice, I have to say!

Emm, looking forward to seeing you soon!