preface

Vite is undoubtedly one of the hottest projects right now, and with the release of version 2.0 after Spring Festival, more and more developers are paying attention to the project. What impressed us most about this next-generation front-end build tool is its speed. The daily grind of slow project start times and HMR, with Vite, really don’t feel too good. Although Vite has nothing to do with the framework, it is still Vue project that is widely used. Then can React project be successfully used? In my spare time in these two weeks, I started the attempt of Vite 2.0 + React. Of course, there are many problems, such as the introduction of Antd, how to write aliases, how to configure agents, the integration of Ahooks and so on. I hope it can help students who want to use React and Vite to improve the development efficiency, and avoid detours. Of course, we can also get an intuitive understanding of Vite’s pre-packaging principle and real experience of performance from the process of practice.

This article source address in vite- Playgrounds, if you find a problem in reading, welcome pr.

During this period, I also participated in the translation of Vite Chinese documents. Interested students are welcome to come to optimize and errata.

And just to make an announcement, During the Spring Festival, I spent time participating in Yu Da’s live video of Open Source Friday on Twitch — Next Generation frontend Tooling with ViteJS ✨ Open Source Friday ✨ subtitle translation work, in the video has especially big about Vite’s various functions in detail, big god online coding, online Debug, big Man Diss webpack and Vite philosophy thinking. The total length of the video is one hour. I don’t have much energy to put into it after the holiday. It is estimated that it will be delivered next week.

Ok, now join me Step by Step into the Vite 2 + React combat tour.

Initialize the project

$ npm init @vitejs/app
Copy the code

Select the project name and template:

Install dependencies and start:

$ cd vite-react
$ npm install
$ npm run dev
Copy the code

Add Babel, React, and Webpack-dev-server to the React environment using Vite.

Added Antd climb pit note

Style climb pit

$ npm install antd
Copy the code

Introduce ANTD in app.jsx:

import { DatePicker } from'the antd';Copy the code

After saving, reload the page, note that this is not HMR, and Antd has been introduced:

Then we add the DatePicker and find no style:

Follow the antD documentation to introduce CSS styles, which are slightly better, but still not normal:

If you attempt to introduce Less, you will hear an error:

Vite has built-in support for Less, but it requires you to install Less manually. See Features # CSS pre-processors

$ npm install -D less
Copy the code

After the installation restarts, there is a new error:

That’s a familiar smell. That’s an Antd error. That’s right. The error message indicates that the Issue can be viewed. It has not been viewed for two years, but the Issue is getting bigger and bigger, because the less-loader upgrade has brought new pits. The solution is to start javascriptEnabled in webPack’s less-loader. See the Commit

Add the following configuration to the Vite. Config.js file:

// vite.config.js.css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true},}}...Copy the code

Finally, the pattern works:

About using full quantitiesAntdBao’s warning analysis

Another point to note is that when you open the debug window, another familiar warning appears, which is not unfamiliar to any of you who have used Antd development in the early days:

The original project was using WebPack. After webpack@2, the tree shaking of the ES module is supported. This warning does not appear.

In Vite, we can look at the official documentation, and Vite prebuilds and overwrites the NPM dependency as a legal URL. For this project, Vite prebuilds Antd into the /node_moduls/.vite folder and rewrites the URL to /node_modules/.vite/antd.js? V = D2A18218, hence the warning.

Don’t worry though, tree shaking will still happen in the production package. Even if a full Antd package is introduced into the development environment, Vite’s esBuild-based precompilation is extremely fast, and the browser will cache the package later, improving the development experience rather than reducing it. This warning can be ignored.

Replace the topic

Try changing the subject again:

According to the guidance of the official website, use less modifyVar to overwrite the less variable, so as to achieve the purpose of changing the theme. Customizable theme-Ant Design and Webpack configuration are different in less-Loader, it is much simpler in Vite. It is still configured in less option:

// vite.config.js.less: {
        javascriptEnabled: true.modifyVars: {
          "primary-color": "#1DA57A"."link-color": "#1DA57A"."border-radius-base": "2px",}},...Copy the code

You can see the style in effect:

With this in mind, we made it easier to change the theme to dark:

import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
import { getThemeVariables } from "antd/dist/theme";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [reactRefresh()],
  css: {
    preprocessorOptions: {
      less: {
        javascriptEnabled: true.modifyVars: {
          ...getThemeVariables({
            dark: true,}),... {"primary-color": "#1DA57A"."link-color": "#1DA57A"."border-radius-base": "2px",},},},},},},});Copy the code

No problem, dark theme works:

The proxy can be accessed in RESTFul mode

Refer to the configuration of server.proxy on the official website. It should be noted that the writing method of proxy is slightly different from the configuration of the proxy in webpack-dev-server we used before, as follows:

// vite.config.js
  server: {
    proxy: {
      '/api': {
        target: 'http://jsonplaceholder.typicode.com/'.changeOrigin: true.rewrite: (path) = > path.replace(/^\/api/.' '),}}},Copy the code

At this time we visit http://localhost:3000/api/users, you can access to the data of jsonplaceholder.typicode.com/users

Integrated the React the Router

Let’s add a menu and a route, first introduce the React Router:

$ npm i react-router-dom
Copy the code

Create index.jsx file:

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import App from "./App";

export default function Index() {
  return (
    <Router>
      <Switch>
        <Route path="/app">
          <App />
        </Route>
      </Switch>
    </Router>
  );
}
Copy the code

Modify the main. JSX file to replace App with Index:

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
- import App from './App'
+ import Index from './index'

ReactDOM.render(
  <React.StrictMode>
- 
      
+ 
      
  </React.StrictMode>,
  document.getElementById('root')
)
Copy the code

Now visit http://localhost:3000/app can access to the App page, routing to take effect.

Let’s add another menu and create a new layout.jsx file:

import React from "react";
import { Menu } from "antd";
import { Link } from "react-router-dom";

export default function Layout() {
  return (
    <Menu selectedKeys="App" mode="horizontal">
      <Menu.Item key="App">
        <Link to="/app">App</Link>
      </Menu.Item>
    </Menu>
  );
}
Copy the code

Finally, introduce the Layout file in index. JSX, as shown in the Commit

Note the use of aliases — breaking change

Note that the userconfig. alias for Vite@2 is out of date and is written differently than that for Vite@1. See the resolve-alias and rollup plugins documentation on the official website

// vite.config.js.import path from "path"; .resolve: {
    alias: [{find: / ^ ~ /,
        replacement: path.resolve(__dirname, "src"),},],}...Copy the code

Then we adjust the file structure and use aliases instead of relative paths, as shown in the Commit

User List page

Next, we develop a list of users that simulate the real interface, and refer to umi@2 + dva to complete the steps of user-managed CURD application

Create a User page

Add the User route and page as shown in this Commit.

At this time to visithttp://localhost:3000/userYou’ll see what’s been addedUserPage:

Request interface climb pit

Request interface data, here using ahooks use-request

NPM 7 (NPM 7) :

Because NPM 7 automatically installs the peerDependency, ahooks’ peerDependency is react@^16.8.6, which conflicts with the react@17 version of the project. This issue has been fixed in this pr. However, no packets have been sent yet. Temporarily use YARN to bypass this problem:

$ yarn add @ahooksjs/use-request
Copy the code

Now we can use use-request to request/API /users to obtain user information:


  const { data, error, loading } = useRequest('/api/users')

Copy the code

Display data

Once the pit for the interface request is filled, the user information can be displayed. Let’s add a table showing user information, as shown in the Commit.

Use-request returns loading. In combination with antD table component’s loading, it is convenient to handle loading:

At this point, the page for the simulated interface to request data is complete.

Pits about paging

Due to our interface is used to simulate the interface, paging information in the Response Headers, request jsonplaceholder.typicode.com/users?_page… You can see:

I checked the Ahooks API and found that there is no handling function for Response Headers. I checked the source code and found that there is no way to get the values in Headers:

In the real interface, the paging information is usually in the Response Body, so the paging data is easy to process, and the pit is not time-consuming to fill.

What Else

It’s not over, of course, but the rest of the process is fairly routine, as listed below:

  • integrationRedux, or use encapsulateddva.js
  • Reductive routing
  • Do you rememberbabel-plugin-importNow, inViteIf you want styles to load on demand, you can try using this plugin:vite-plugin-style-import, has now been supportedVite 2
  • Want to useTypeScript, can be used@vitejs/create-appreact-tsTemplate, and then follow the steps in this article
  • Production Mode,SSR, refer to the official website configuration, what pits can be discussed together