Generate the React project using Vite

Use the commands provided by the authorities

yarn create @vitejs/app
Copy the code

Then make a selection based on your needs. We chose the React-TS template here

The React syntax is only supported. We also need other configurations to complete the Setup of the React project

TypeScript

When building a React project with scaffolding, there is an option to build the React-TS version. It is recommended that you choose the React-TS version directly so that you can skip this section.

If you choose the React version, see the configuration below (not necessary, just choose TS version).

Vite itself supports Typescript syntax, but it only compiles, not validates. If you want to validate TS syntax, you can use TSC –noEmit command to validate TS syntax. If you want to validate TS syntax, you can use TSC –noEmit command to validate TS syntax

// test.ts

interface A {
    name:string
}

export const a:A={
    name:'fishfan',
    age:'18'
}

Copy the code

This code obviously has a TS syntax error, you can see the error in the editor (VScode comes with an error), but the browser will still work.

We need to install typescript

yarn add typescript @types/react @types/react-dom -D
Copy the code

Then modify the packaging command in package.json

  "scripts": {
    "dev": "vite",
    "build": "tsc && vite build",
    "serve": "vite preview"
  },
Copy the code

Create tsconfig.json in the root directory

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": false,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["./src"]
}

Copy the code

This will alert you to errors at packaging time

style

Vite supports CSS variable and postCSS

For DETAILS about CSS Carunavailable, see this link

Install related plug-ins

yarn add  postcss-preset-env autoprefixer  -D   
Copy the code

The Vie has Postcss inside it. If we want to use another plugin for Postcss, create postcss.config.js in the root directory as follows, depending on the project.

module.exports = {
  plugins: [
    require('autoprefixer'),
    require('postcss-preset-env'),
  ],
};
Copy the code
autoprefixer

This need not say more, must install one of plug-ins. Easy to write standard CSS, it will provide you with a very complete hack compatibility scheme. Of course, one thing to understand here is that most of its compatible data sources are Can I Use. Another plug-in configuration parameter to understand is Browsers, but typically we configure browser version information in package.json.

Add the following example to package.json so that other plug-ins can get the version that the project will be compatible with

"Browserslist ": ["> 1%", // Global browser usage is greater than 1%." Last 2 versions" // Two latest versions of each browser.Copy the code
postcss-preset-env

Postcss-preset -env is used to help PostCSS find the configuration in package.json’s BrowserList and load the specified CSS compatibility styles

css Module

Create a CSS file named [name].module. CSS will be recognized as a CSS module, if your CSS file name is not defined in this way, you will not be able to use the CSS Module

If verified? Create a CSS file called app.module.css

// app.module.css
.text {
  color: red;
}

Copy the code
// app.jsx

import { useState } from 'react';
import styles from './app.module.css';

function App() {
  return <div className={styles.text}>hello fishfan</div>;
}

export default App;

Copy the code

If you remove the Module field, you’ll find that CSS styles don’t work

CSS preprocessing tools such as LESS Sass

If you want to use whichever preprocessor you want to install, let’s take less as an example

yarn add less -D
Copy the code

Once installed, you can use less without additional configuration.

eslint & prettier

Eslint is used to standardize the writing format of code, a must for team projects! Pritter automatically formatted it for us

eslint

Create.eslintrc.js files in the root directory. Eslint rules can be written by us. For details about how to configure esLint, click here

Here, just follow my package.json to install

Packag. json is configured as follows

{" name ":" vite ", "version" : "0.0.0", "scripts" : {" dev ":" vite ", "build" : "TSC && vite build", "serve" : "vite preview", "lint:fix": "eslint ./src --ext .jsx,.js,.ts,.tsx --quiet --fix --ignore-path ./.gitignore", "lint:format": "prettier --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\" ", "lint": "Yarn lint:format && yarn lint:fix ", "type-check":" TSC "}, "dependencies": {"react": "^17.0.0", "react-dom": "^ 17.0.0"}, "devDependencies" : {" @ types/react ":" ^ 17.0.0 ", "@ types/react - dom" : "^ 17.0.0", "@ typescript - eslint/eslint - plugin" : "^ 4.28.2", "@ typescript - eslint/parser" : "^ 4.28.2", "@ vitejs/plugin - react" : "^ 1.0.0", "eslint" : "^ 7.30.0", "eslint - config - prettier" : "^ 8.3.0 eslint - plugin -", "HTML" : "^ 6.2.0", "eslint - plugin - import" : "^ 2.23.4", "eslint - plugin - JSX - a11y" : "^ 6.4.1 eslint", "- the plugin - node" : "^ 11.1.0", "eslint - plugin - prettier" : "^ 3.4.0", "eslint - plugin - promise" : "^ 5.1.1," "eslint plugin - react" : "^ 7.24.0", "eslint - plugin - simple - import - sort" : "^ 7.0.0", the "pre - commit" : "^ 1.2.2", "prettier" : "^" 2.3.2, "typescript" : "^ 4.3.2", "vite" : "^" 2.6.4 "}}Copy the code

Create the esLint rule file.eslintrc.js

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  env: {
    browser: true,
    amd: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:jsx-a11y/recommended',
    'plugin:prettier/recommended', // Make sure this is always the last element in the array.
  ],
  plugins: ['simple-import-sort', 'prettier'],
  rules: {
    'prettier/prettier': ['error', {}, { usePrettierrc: true }],
    'react/react-in-jsx-scope': 'off',
    'jsx-a11y/accessible-emoji': 'off',
    'react/prop-types': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    'simple-import-sort/imports': 'error',
    'simple-import-sort/exports': 'error',
    'jsx-a11y/anchor-is-valid': [
      'error',
      {
        components: ['Link'],
        specialLink: ['hrefLeft', 'hrefRight'],
        aspects: ['invalidHref', 'preferButton'],
      },
    ],
  },
};

Copy the code

Create files that do not need to be detected by ESLint

node_modules
.DS_Store
dist
dist-ssr
*.local
node_modules/*
Copy the code

A lot of our code doesn’t conform to the specification, so you have to change it manually one by one (or fix it with esLint at commit time), which is cumbersome, and we want to fix it automatically when we save it.

That’s where Prettier comes in

prettier

Prettier can be found here

The first thing we need to install in VScode is the Prettier plug-in

The. Prettierrc. js file in the root directory contains the following content, and you can configure rules according to your own requirements

module.exports = {
  semi: true,
  trailingComma: 'all',
  singleQuote: true,
  printWidth: 90,
  tabWidth: 2,
  jsxBracketSameLine: true,
  endOfLine: 'auto',
};

Copy the code

Prettierignore also creates a file that ignores the fix

node_modules
.DS_Store
dist
dist-ssr
*.local
node_modules/*
Copy the code

Open VScode autosave configuration

The first step is to open the set search format on Save

Formatter ** select prettier

Prior to committing code, rule checking can ensure that code entering git repositories is compliant, but projects can run Lint slowly, and Lint-staged projects can be fast by having Lint only detect files in staging

Install Husky and Lint-staged

yarn add husky lint-staged -D
Copy the code

Package. json add the following configuration

  "husky":{
    "hooks":{
      "pre-commit":"lint-staged"
    }
  },
  "lint-staged":{
    "*.js":"eslint --fix",
    "*.ts":"eslint --fix"
  },
Copy the code

When files change and we git commit them, the pre-commit hook will fire and execute Lint-staged commands.

resolve

alias

Path alias is similar to the alias function in Webpack. When the project is complex, if you want to import the outermost file in the deep file, for example, we can set SRC to the directory, identified by the @ character

import untils from '.. /.. /.. /.. Import untils from '@/util' // after using the aliasCopy the code

extensions

You can ignore the import extension with extensions, for example

Import App from './app.jsx // Not using extensions Import App from './ App // Using extensionsCopy the code

Modify the vite. Config. ts file

 // vite.config.ts
 
 
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  resolve: {
    extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
    alias: {
      '@': '/src',
    },
  },
})

Copy the code

server

What we need to focus on in the configuration of server is proxy, request proxy, if we don’t set proxy, then we send requests across domains.

 server: {
    proxy: {
      '/api': {
        target: 'https://www.xxx.xxx',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
    }
  }
Copy the code

With this configuration in viet.config.js, your request URLS that start with **/ API ** will be forwarded to www.xxx.xxx.

How to use a React route and Antd in a React project

See the article below at juejin.cn/post/693867…

routing

The react-router-dom installation is preferred

Yarn add react-router-dom -d // This is the latest version of react-router-dom. My version is 6.0.2Copy the code

The latest version of react-router-dom (after 6X) does not provide the Switch component but uses Routes. For details about the difference between react- Router-dom 5x and 6x, please click the link below

Link 1

Link 2

Links to 3

Create the Home and About folders under the SRC file and create the corresponding files

/src/Home/index.tsx

import React from 'react'

export default function index() {
  return (
    <div>
      Home
    </div>
  )
}

Copy the code
/src/About/index.tsx

import React from 'react'

export default function index() {
  return (
    <div>
      About
    </div>
  )
}

Copy the code

The root directory creates the route.tsx file

Here I need to explain why the route file is TSX file instead of TS file. The main reason is that I need to use components directly inside the route file. I used to export functions and then execute functions inside the route file. Vite is not compatible with the latest react-route-DOM.

// route.tsx import Home from '.. /src/Home' import About from '.. /src/About' const routes = [ { path: "/home", component: Home }, { path: "/about", component: About } ]; export default routes // App.tsx import React from 'react' import { Route, Routes } from "react-router-dom"; import routes from './route' import './App.css' function App() { return ( <div className="App"> <Routes> { routes.map(item => { return <Route path={item.path} key={item.path} element={item.component()}/> }) } </Routes> </div> ) } export default AppCopy the code

There’s no problem writing it

// route.tsx import Home from '.. /src/Home' import About from '.. /src/About' const routes = [ { path: "/home", component: <Home/> }, { path: "/about", component: <About/> } ]; export default routesCopy the code

Modify the app. TSX file

import React from 'react' import { Route, Routes } from "react-router-dom"; import routes from './route' import './App.css' function App() { return ( <div className="App"> <Routes> { routes.map(item => { return <Route path={item.path} key={item.path} element={item.component}/> }) } </Routes> </div> ) }  export default AppCopy the code

Modify the main. TSX file

import React from 'react'
import ReactDOM from 'react-dom'
import {BrowserRouter} from 'react-router-dom'
import './index.css'
import App from './App'

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
)

Copy the code

You will see your route to visit http://localhost:3000/home and http://localhost:3000/about

Using Antd

Install ANTd and @ant-Design/ICONS. After antd 4x, the ICONS libraries are separated from ANTD itself and need to be installed separately

yarn add antd @ant-design/icons
Copy the code

Introduce ANTD in app.tsx files

import React from 'react'
import { Route, Routes} from "react-router-dom";
import routes from './route'
import { Button } from 'antd'
import './App.css'

function App() {
  return (
    <div className="App">
      <Button type="primary">fishfan</Button>
        <Routes>
          {
            routes.map(item => {
              return   <Route path={item.path} key={item.path} element={item.component}/>
            })
          }
        </Routes>
    </div>
  )
}

export default App

Copy the code

You will find

That’s because we didn’t introduce the ANTD style. We introduced the ANTD style in main.tsx

// main.tsx
import 'antd/dist/antd.css'
Copy the code

Style is working!! But run the package command

yarn build
Copy the code

If we look at the size of the packaged CSS, which is over 500 KB, it is clear that the style is not loaded on demand.

Antd style implementations are loaded on demand

Please note that we are using less here. If you are using CSS, the following configuration will need to be modified

Install vite – plugin – imp

yarn add vite-plugin-imp -D
Copy the code

Modify the vite. Config. Js

import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import vitePluginImp from 'vite-plugin-imp'  // https://vitejs.dev/config/ export default defineConfig({ plugins: [ react(), vitePluginImp({ libList: [ { libName: "Antd ", style: (name) => 'antd/lib/${name}/style/index.less',},],}), CSS: { preprocessorOptions: { less: { javascriptEnabled: true, } } }, })Copy the code

Remove main.tsx to introduce ANTD-style code

The import 'antd/dist/antd. CSS' deleteCopy the code

After running the package command, you can find that the size of the CSS is reduced to about 40kb.

How do I change the global style of ANTD

Modify the CSS configuration in vite.config.js and add the modifyVars object, whose variables are antD global variables

  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        modifyVars:{
            'primary-color': '#ff704c',
            'link-color': '#ff704c',
            'border-radius-base': '4px',
        }
      }
    }
  },
Copy the code

We will notice that the global theme color of our Settings has changed, indicating that our configuration is working

End to end

Project address: github.com/wuqiren/fis…