Post

A Brief Analysis of Vite's Principles

A Brief Analysis of Vite's Principles

I use Vite as a build tool in my work projects, and the results are good. I studied the general principles and recorded them.

1 What is Vite

1.1 Existing issues

As we start building larger and larger applications, the amount of JavaScript code we need to process grows exponentially. Large projects containing When using JavaScript-based development tools such as Webpack, you start to encounter performance bottlenecks: it often takes a long time (even minutes!) to start the development server, and even with hot module replacements. it often takes a long time (even minutes!) to start the development server, and even with hot module replacement (HMR), it takes several seconds for the effects of file modifications to be reflected in the browser.

The current project is built using webpack and takes 2 minutes and 20 seconds to cold start. When I go to make a cup of tea and come back, I often forget what I When I go to make a cup of tea and come back, I often forget what I just wanted to do.

1.2 A new generation of build tools

Vite is a new generation of front-end construction tools. It has the characteristics of extremely fast service startup and lightweight and fast It has the characteristics of **extremely fast service startup and lightweight and fast hot reload, providing extremely fast response for development.

In the project, it can be started within 1 second according to the actual test. Once you experience the speed of Vite, there’s no going back.

Vite and webpack

2 Vite principle

2.1 Browsers begin to support ESM natively

The browser supports ESM, which is the main background for Vite to achieve extremely fast cold start and hot reload.

Before browsers supported ES modules, JavaScript did not provide a native mechanism for developers to develop in a modular manner.

As shown in the figure below, you can see the changes in front-end construction tools.

Brief history of construction tools

  • No modularity: JS inline and external methods require manual maintenance of the order in which dependencies are introduced.
  • Runtime modularization AMD/CMD: RequireJs and SeaJS appear, using an asynchronous method to load modules.
  • Nodejs appeared, and the first batch of build tools appeared (Grunt/Gulp). js can handle code compression, compression, and compilation. js can handle code compression, compilation, unit testing and other tasks. * Browserify, implements a new version of the
  • Browserify, implements browser-side CommonJS specifications
  • The ESM specification appears, webpack, and Rollup appear. Webpack supports AMD\CommonJS\ESM, babel, style preprocessing and various MVC frameworks, becoming mainstream. frameworks, becoming mainstream. Webpack supports AMD\CommonJS\ESM, babel, style preprocessing and various MVC frameworks, becoming mainstream. * ESM browser native support, esbuild appears, and build tools (Vite, Snowpack) that rely on esbuild appear.

See detailsA brief history of front-end build tools.

2.2 Extremely fast service cold start

Vite improves development server startup time by classifying modules in an application into dependencies and sources at the outset.

  • Dependencies are mostly pure JavaScript that does not change during development. Some larger dependencies (such as component libraries with Some larger dependencies (such as component libraries with hundreds of modules) are also expensive to deal with. Dependencies also often exist in multiple modular formats (such as ESM or CommonJS). Dependencies also often exist in multiple modular formats (such as ESM or CommonJS). * Source often contains files that are not directly JavaScript and need to be transformed (such as JSX, CSS or Vue/Svelte components), and are often At the same time, not all source code needs to be loaded at the same time (such as code modules based on route splitting).

2.2.1 Preprocessing dependencies

Vite uses esbuild to pre-build dependencies. esbuild is written in Go and is 10-100 times faster than pre-building dependencies with packagers written in JavaScript.

esbuild

2.2.2 Dev server based on ESM

Traditional packaging tools such as Webpack first parse dependencies, package and build, and then start the development server. When we modify a submodule in the bundle module, the entire bundle file will be repackaged and output.

The larger the project application, the longer the startup time. The larger the project application, the longer the startup time. webpack server Vite takes advantage of the browser’s support for ESM. When a module is imported, the browser will download the imported module. Start the development server first, and then request the file of the corresponding module when the code is executed until the module is loaded. In essence, dynamic loading is achieved. The gray part is the route that is not used yet, so this part will not participate in the construction process.

As there are more and more applications in the project, adding routes will not affect its construction speed. vite server vite server

For files that the browser cannot directly recognize, such as tsx, scss. How to deal with Vite?

  • After reading the contents of the index.tsx file, Vite will compile the contents of the file into code that the browser can recognize. At the same time, an import statement represents an HTTP request. The Vite Dev Server will read the local file and return a code that the browser can parse. parses the new import statement, it will issue a new request, and so on, until all resources are loaded.

code fromcodesandbox

vite-tsx

  • For style preprocessing files such as scss, Vite will compile them into js files that comply with ESM and can be recognized by the browser.

vite-scss

P.S. Since Vite targets modern browsers (development environments) only, it is recommended to use native CSS variables and PostCSS plugins that implement CSSWG drafts (such as postcss-nesting) to write simple, future-proof CSS. You can try replacing SCSS in the future.

2.3 Fast hot reload

All current packaging tools have similar ideas for implementing hot updates: mainly creating communication between the browser and the server through All current packaging tools have similar ideas for implementing hot updates: mainly creating communication between the browser and the server through WebSocket.

  1. Create a websocket server and client files and start the service
  2. Monitor file changes through chokidar
  3. When the code is changed, the server makes a judgment and pushes it to the client. 4.
  4. Updates where the client performs different operations based on the pushed information

Vite hot update

The hot update construction process in Vite is similar. Vite starts the Vite Server service locally, connects and communicates with the browser through WebSocket, and adds WebSocket’s scheduled heartbeat detection mechanism to obtain the modified and updated file path and timestamp identifier, and then takes the timestamp as a parameter to re-request the modified version of the file to prevent caching.

Vite hot update

2.3.1 Dev server based on ESM

The main difference is that when Webpack receives a hot update notification, it starts from the entry entry file, packages the resource files it depends on through the loader, and then passes them to the client for running through the server. It is precisely because of this operating mechanism that the update speed will plummet as the application size increases. speed will plummet as the application size increases.

The problem of slow hot update of Webpack can be significantly improved through the babel-plugin-dynamic-import-node plug-in, or by manually implementing dynamic on-demand loading (modifying the entry to the part or module that needs to be compiled in the current project), the hot update speed can also be greatly improved, but it still requires rebuilding this part and reloading the page.

webpack server

In Vite, HMR is performed on native ESM. When editing a file, Vite only needs to deactivate exactly the link between the edited module and its nearest HMR boundary (most of the time just the module itself), allowing HMR to always be updated quickly regardless of app size.

vite server

2.3.2 Using browser cache

Vite also utilizes HTTP headers to speed up full page reloads (again letting the browser do more for us).

  • Requests for source code modules will be negotiated and cached based on 304 Not Modified
  • Dependent module requests will be strongly cached through Cache-Control: max-age=31536000,immutable, so once they are cached they will not need to be requested again.

2.4 Production environment

For optimal loading performance in production environments, Vite uses Rollup packaging. reason.

  • There are still some browsers that do not support native ESM.

caniuse

  • Publishing an unpackaged ESM in a production environment is inefficient (even using HTTP/2) because nested imports cause additional network round- trips. Compare esbuild: In terms of packaging applications with complex module types
  • Compare esbuild: In terms of packaging applications with complex module types, the ecosystem is more mature and has functions such as code splitting.

Vite does not rule out the possibility of using esbuild for production builds in the future.

3 Compare to other tools

  • WMR: The Preact team’s WMR offers a similar feature set, and Vite 2.0’s support for the Rollup plug-in interface was inspired by it. In terms of scope of use In terms of scope of use , it is more suitable for the Preact framework.
  • @web/dev-server: (formerly es-dev-server) is a great project that inspired the koa-based Vite 1.0 development server. It does not provide official framework integration and requires manual setup of the Preact framework. framework integration and requires manual setup of Rollup configuration for production builds.
  • It does not provide official framework integration and requires manual setup of Rollup configuration for production builds. Snowpack: Also a non-build native ESM development server very similar to Vite. This project is no longer maintained. The Astro team is currently a very active member of our ecosystem and they have helped Vite make a lot of progress. progress.

reference

This post is licensed under CC BY 4.0 by the author.