9
头图
This article first public account "160b4584c41c4a front end from advanced to admission ", welcome to pay attention!

What is the experience of participating in Vue Conf 2021 at this question, I stumbled upon Anthony Fu's answer that mentioned a fun Versailles plugin: vite-plugin-sleep .

Let's take a look at how Anthony Fu leads to this plugin in the answer:

Questions about the meaning of Vite fast in the QA session seem to have sparked some discussion among everyone. I take this opportunity to talk about my own opinions.
We have two words, UX and DX, which correspond to User Experience and Developer Experience respectively.

Indeed, to some extent, as developers, we should give priority to the experience of end users, but as the number of developers increases and software requirements become more complex, the experience of developers as humans is also very important.

If developers can't get good DX, it is difficult to have enough efficiency to improve UX. The performance improvement can better allow the machine to accept human commands instead of wasting time waiting for the machine to complete its work.

Of course, if you think the tool is too fast to affect the rest, here is the plugin of @小炫, let your Vite also rest vite-plugin-sleep (found by you, in fact, shaking this cleverness is my purpose )

This Versailles-scented words really made me laugh. The slow construction of Webpack did give us some good fishing time. Vite was the culprit who took them away. This is belongs to the plug-in !

Introduction

First look at the "motivation" chapter of vite-plugin-sleep:

In the old days with webpack, we had many times when we could compile with pay, and with vite it was so
fast that we couldn't rest.
Time to take a nap in the vite.

In those days with Webpack, we had a lot of time to rest while compiling, but Vite was too fast, took away all of this .

It's time for take a nap ...

usage

yarn add vite-plugin-sleep
// vite.config.ts
import sleep from "vite-plugin-sleep";

/** @see {@link https://vitejs.dev/config/} */
export default defineConfig({
  plugins: [
    // ...other plugins
    sleep(/* options */),
  ],
});

It's that simple, install and import, your fishing time is back.

principle

Take a look at the source code of this plug-in, and learn how to write the Vite plug-in by the way.

The general form of Vite plug-in is generally a function, which accepts an options configuration option passed in by the user, and returns the standard plug-in format of Vite, an object like this:

{
  name: 'vite-plugin-sleep',
  config() { // 自定义 config 逻辑 }
  load() { // 自定义 load 逻辑 },
}

Vite exposes many hook functions to users, allowing users to intervene and change the behavior of the source code at appropriate times.

Read the documentation in the plug-in API-hook section of the official website. Note that some hooks are inherited from Rollup, so you need to go to Rollup's official website to view the instructions.

Explain with the example mentioned in the official website:

export default function myPlugin() {
  const virtualFileId = "@my-virtual-file";

  return {
    name: "my-plugin", // 必须的,将会显示在 warning 和 error 中
    resolveId(id) {
      if (id === virtualFileId) {
        return virtualFileId;
      }
    },
    load(id) {
      if (id === virtualFileId) {
        return `export const msg = "from virtual file"`;
      }
    },
  };
}

This plug-in allows the user to import a virtual file (which does not exist in the actual file), through the load hook to customize the content of the read file, the user can import "from virtual file" this way.

import { msg } from "@my-virtual-file";

console.log(msg);

With these pre-knowledges, let's take a look at how this plugin is written:

import type { Plugin } from "vite";
import type { UserOptions } from "./lib/options";
import { sleep } from "./lib/utils";
import { name } from "../package.json";

export default function sleepPlugin(userOptions: UserOptions = {}): Plugin {
  const options = {
    ...userOptions,
  };
  let firstStart = true;
  return {
    name,
    enforce: "pre",
    configureServer(server) {
      server.middlewares.use(async (req, __, next) => {
        // if not html, next it.
        // @ts-expect-error
        if (!req.url.endsWith(".html") && req.url !== "/") {
          return next();
        }
        if (firstStart) {
          await sleep(options.devServerStartDelay || 20000);
          firstStart = false;
        }
        next();
      });
    },
    async load() {
      await sleep(options.hmrDelay || 2000);
      return null;
    },
  };
}

Actually very simple, configureServer hook Vite is provided by the official unique hook (ie Rollup does not exist in the hook), the hook is used to configure the development server, the most common use case is to add some custom services middleware .

The load hook is Rollup . According to the official website, return null represents that the file is handed over to other plug-ins or processed by the default parsing behavior, that is, nothing is done after a two-second delay.

Back to the content of the plug-in, first define a sleeping function:

export function sleep(delay: number) {
  return new Promise((resolve) => setTimeout(resolve, delay));
}

With the await syntax, a very elegant sleep can be achieved.

Use enforce: 'pre' to force the hook of this plug-in to be executed at the forefront (other plug-ins don't want to prevent me from fishing).

configureServer also very simple. When the Vite development server is started for the first time, when accessing the entry HTML file, sleep sleeps the time passed by the user, which is 20 seconds by default. (Why is 20 seconds enough? XD, please set it to 120 seconds.)

The official example is to add middleware, but Boss You never thought that after the comment code in the middle was filled by the little fisherman, it was actually used to do this kind of thing!

After that is the load hook. When reading each file, it sleeps for 2 seconds by default.

It's that simple, a Vite fishing plug-in is complete.

to sum up

It’s the weekend, have fun with this Versailles plug-in, and learn the basics of the Vite plug-in by the way. It’s great!

Thank you everyone

Welcome to follow ssh, front-end trends, and original interview hot articles.

Remember to add my friends after following, I will share front-end knowledge and industry information from time to time. 2021 will spend with you.


ssh_晨曦时梦见兮
1.6k 声望498 粉丝