Vite is a build tool used by vue3 when it was released

I believe that the production process of vite is quite clear, now to the depth of the analysis of the Vite he really good where, let you greatly so hard to promote him

What does vite do

First of all, Vite is primarily used as an alternative to WebPack during development and release

While the production environment is still packaged by rollup, in the development environment, vite’s own mode is used to correct the webPack problem of taking too long to package dependencies

You can see it here

  1. Vite is a build tool based on development environment
  2. Vite is not a complete replacement for Webpack, but rather an optimized version of Webpack-dev-server

Why is there no substitute for Webpack

At least for now, Vite has no ability to replace Webpack at all. Vite itself is still too fragile, both in terms of community and capability, and its generation and popularity are entirely dependent on vue’s own heat

Think about what problems you need to solve if you want to switch from WebPack to Vite.

Problems with plug-ins

For Vite it is a plug-in, but for WebPack it is a loader

Let’s take a look at how Vite handles its plugins

// Brief a few plug-ins
const resolvedPlugins = [
   ...(Array.isArray(configureServer) ? configureServer : [configureServer]), ... (transforms.length ||Object.keys(vueCustomBlockTransforms).length
      ? [
          createServerTransformPlugin(
            transforms,
            vueCustomBlockTransforms,
            resolver
          )
        ]
      : []),
    assetPathPlugin,
    webWorkerPlugin,
    wasmPlugin,
    serveStaticPlugin
  ]
  resolvedPlugins.forEach((m) = > m && m(context))
Copy the code

Looking at this code, it’s not hard to spot a few problems

  1. Vite’s server-side code is based on KOA, and all of its plug-ins are based on that. However, as we know, KoA plug-ins are divided into two stages by next to execute the code. As a result, when you write a new plug-in, you have to think about the impact of your plug-in before and after. The current source is passed forward after each loader completes execution
  2. Those familiar with Webpack know that each loader is a function, that is to say, to parse a file. But if we follow the current plug-in mode of Vite, each plug-in may handle multiple functions. For example, if we need to implement the ability of webPack to parse SCSS files, Then it is necessary to implement the capabilities of Sas-loader, CSS-loader and style-loader in a plugin, and then return the file after parsing, which is relatively poor for the reusability of plug-ins
  3. Useless plug-ins are still executed, so that even if only one plug-in parses a file, other plug-ins can still be preloaded

Webpack plug-in

Webpack has been used for so many years that its community is well-established enough that most companies have custom plugins based on WebPack development. Switching to Vite from scratch would mean reorganizing the plugins that you wrote before and might not be able to reuse them at all. This resulted in additional development costs or changes to our entire build process that were not worth the cost of the upgrade

Besides, there are so many people in the WebPack community providing so many plugins and loaders that I don’t think it’s a good idea to replace WebPack with Vite right now, but vite may be the way to go

The advantage of vite

Having said that, Vite is no substitute for WebPack, but it’s certainly not as bad or reusable as it sounds

First of all, based on the test of the development environment, we know that webpack is in the situation of more and more files, and the dependency level is getting deeper and deeper. Each packaging will take longer, which affects our efficiency in development. Sometimes we only modify one document, but it takes at least several minutes to package, which is unbearable

What is vite optimized for

Vite is optimized for this, instead of being packaged when launching the development environment, it borrows the browser’s ES import

Let’s take a look at how import is represented in the browser.

<script type="module">
  import test from './test.js';
</script>
Copy the code

When we use a script tag with type module in the browser, the import inside it is converted to a browser request

Vite does a series of content based on this, and briefly describes the process

  1. Use the browser’s ES import capability to intercept the current request
  2. Get the current file
  3. Parse corresponding files according to different file types

This is vite in file is accessed when several things happened by koa middleware, analyses the different types of files, and generate the source code is returned to the browser to display, generally in terms of parsing a document, and the speed is very fast, so vite can be hard to feel when using him in the analytical process of waiting, Is a hot flush service at the millisecond level

Vite hot update

As mentioned earlier, Vite only parses the currently changed files during the update process, so how does it modify the files and change the changes on the page

First of all, when the application starts, Vite will start two services locally, one is the front-end path service, and the other is the back-end service of file parsing. The two services are connected using WebSocket

Whenever the page content is modified, it triggers file listening for the backend service using the Chokidar library (check it out).

The specific content is in the HMR plug-in. Watch is used to monitor files internally. Except for VUE and CSS, hot update monitoring of other file types is under ServerPluginhMr.ts

watcher.on('change'.(file) = > {
  if(! (file.endsWith('.vue') || isCSSRequest(file))) {
    // everything except plain .css are considered HMR dependencies.
    // plain css has its own HMR logic in ./serverPluginCss.ts.
    handleJSReload(file)
  }
})
Copy the code

Vue and CSS are written separately in the corresponding plug-in, independent hot update processing

After the server obtains file updates, it pushes them to the client and processes them according to different types

  1. vue-reload
  2. vue-rerender
  3. style-update
  4. style-remove
  5. js-update
  6. custom
  7. full-reload

The processing for VUE is to update components directly using the update method in VUe3.0

How do I extend Vite

After the above statement, we know that vite hot update is dependent on several aspects

  1. Websocket long connection
  2. Koa middleware compilation

Knowing these two approaches, we were able to extend vite one layer at a time with just a few things to do

The first step is to compile the file type based on the KOA middleware (configureServer can be used to add plug-ins)

import { ServerPlugin } from '. '
import { isImportRequest } from '.. /utils'

export const wasmPlugin: ServerPlugin = ({ app }) = > {
  app.use((ctx, next) = > {
    if (ctx.path.endsWith('.wasm') && isImportRequest(ctx)) {
      ctx.type = 'js'
      ctx.body = `export default (opts = {}) => {
        return WebAssembly.instantiateStreaming(fetch(The ${JSON.stringify(
          ctx.path
        )}), opts)
          .then(obj => obj.instance.exports)
      }`
      return
    }
    return next()
  })
}
Copy the code

This is a plug-in that processes WASM files, mainly based on the file type and then changes the return value content, in the middle of the process is our compilation process

After the plugin is written, the next step is to change the content of the file by listening to it on the client side

After vite starts, its main.js file loads the contents of the file, which accepts the information returned by webSocket according to the createHotContext method and modifs the current component

According to this logic, we can add a JS file, internal socket with the server link, listen to the file we need to return, and do the corresponding operation

This allows you to complete a custom, not just vUe-based Vite

At the end

Vite is a new technology, its community is thriving and the various types of plugins are not yet developed. I think it is impossible to replace WebPack directly now, after all, WebPack has been used for so long, the basic content and usage habits are all in place, but Vite is really strong. For greater development efficiency, consider using Vite in conjunction with WebPack, or if you bring vite ideas to Webpack, this can be a long process to explore