Learn vite in 5 minutes

composition

Why does vite use both esbuild and rollup?
esbuild is used in the development phase (vite dev), and is mainly used to precompile third-party dependencies and compile typescript code in business code. While smoothing out the grammatical differences of third-party dependencies (third-party dependencies are not necessarily ESM syntax), esbuild ensures the development speed of vite dev.
rollup will only be built during vite build, mainly to build packages that can be used stably in the production environment. Rollup is still used because rollup is mature and stable and has a large number of excellent plug-ins.

development server

Principle: browser supports esm module

Vite does not build during development, but converts all content into esm content, and relies on the browser to identify it by itself, just like the live server opens the local index.html file.
For example, index.html imports a picture, and vite asks the browser to import the file from the original location of the picture on the disk. When webpack is developed, it will execute the build, and also import a picture. Because of the build, the picture will be placed in the img folder at the same level as index.html.

Vite handles dependencies through the browser's native recognition of esm, what else does it do?
Building it natively through the browser is fine, but there are two serious problems:

  1. Browsers don't recognize other files, such as .vue files.
  2. js depends on third-party packages, the browser will send too many network requests. For example, to import lodash, you must first write out the full path under node_modules to import, which is a very inconvenient place; what is more serious is that the entry file of lodash depends on many other modules, and the browser will initiate requests to download them one by one. There are many requests for these modules.

Based on the browser's native support for esm, vite solves the above problems and provides a more convenient way.

Summary:
Browsers natively support esm. More accurately, browsers support modularization and engineering. Since browsers support modularity, why do we need to structure our code as it was in the days of jQuery development? Obviously not necessary. This is the biggest difference between vite and webpack.
When vite is developed, it is like an enhanced version of the live server , just like we usually open the live server, the entry file is html, and the files imported in html let the browser parse and import.
In webpack, the html file is just a simple template, and the real entry point is a bloated js file. When developing, the browser opens the standard project structure in the period when the front end was not engineered.

|-js
|-img
|-css
|-index.html

other types of files

Because the bottom layer of vite uses the browser to support esm for engineering, vite does not need any loader for css files and image files, because the browser is behind it to identify them, as long as the browser can directly recognize these files.
For less, postcss, and ts files, you only need to install their corresponding processing programs, such as the less command-line tool. When it converts a less file into a css file, the browser can recognize it.
But when viewing the request in the browser network request, the requested file name is still xxx.less, but the content inside is actually css content, not less. If you think about it, it must be less. The browser doesn't know less at all. But the styles are implemented correctly, so there must be css content inside. It is indeed css content to open the file to view.

request forwarding

The reason behind this is that for browsers, html is the entry file, and src in html requests less, so the network request is of course less. But, we can't let the browser request the less file, right? So vite actually forwards the request, so that the browser actually requests the css file generated by the less conversion. This is why it is said that vite is an enhanced version of the live server, because if it is a live server, it must be stupid to request the less file.
The demand for forwarding requests is very large, so vite changed the development server from version 1.0 of koa to version 2.0 to connect, because connect is more suitable for forwarding requests.

basic use

Install

Vite is based on node, so you need to install node first.

Install the vite tool:

  • npm i vite -Dpartial installation
  • npm i vite -GGlobal installation

Start the project with vite:

  • npx vite

vite will start the development server to request index.htmlthe file in the root directory, and use this file as the entry point to process dependencies.

feature

Depends on pre-built

During development, vite will use esbuild to pre-build some dependencies into esm modules. For example, some third-party packages.

Additionally, @rollup/plugin-commonjs is used for production builds.

Why prebuild? There are two reasons:

  1. Compatibility: During the development phase, Vite's development server treats all code as native ES modules. Therefore, Vite must first convert dependencies published as CommonJS or UMD to ESM. And perform intelligent import analysis.
  2. Performance: Vite converts ESM dependencies with many internal modules into a single module to improve subsequent page load performance. For example, lodash-es above has more than 600 modules. By pre-building it as a module, we only need one HTTP request.

In terms of improving development performance, vite also uses caching.
Filesystem caching
Vite will cache pre-built dependencies to node_modules/.vite.
image.png
vite depends on the data source to decide whether to re-run the pre-build steps:

  • The list of dependencies in package.json, such as a newly installed package
  • The lockfile of the package manager, such as package-lock.json, yarn.lock, or pnpm-lock.yaml
  • Configure in relevant fields of vite.config.js

The pre-build needs to be re-run only if one of the above changes.
If for some reason you want to force Vite to rebuild dependencies, you can --forcestart the development server with a command line option, or manually delete the node_modules/.vite directory.

Browser cache
The parsed dependency requests will be strongly cached with the HTTP header max-age=31536000, immutable to improve page reload performance during development.

  • Once cached, these requests will never reach the development server again.
  • If different versions are installed (this is reflected in the package manager's lockfile), the additional version query field automatically invalidates them.

If you want to debug dependencies via local editing, you can:

  • Temporarily disable caching via the Network tab of the browser debugging tool;
  • Restart Vite dev server, and add --forcecommand to rebuild dependencies;
  • Reload the page.

HTTP cache
chestnut:
image.png
As can be seen from the above request, the pre-built package is requested from .vite, and there is only one network request. And there is a query in the url, indicating the current module version. When the module changes, it will automatically request the latest version.
And the response from the development server requires caching.
image.png
When the page is refreshed, the same module is loaded from the cache, and no request is sent, not even the request header. Once the package is cached, the request does not reach the development server.

preview

vite is based on the project structure packaged by production vite build, which is also a traditional structure. After all, this structure is truly universal.
For this kind of build product, if you want to preview it, you generally use a live server, but vite has this function built in.

  • npx vite preview: Open a local service to preview the packaged effect.

vite VS webpack

Development environment ⚡️Speed ​​improvement
Tools developed with JS usually take a long time to start the development server, and this startup time is positively related to the amount of code and code complexity. Even with HMR, it takes a few seconds for the modified file to be reflected in the browser, such as Webpack. So how does Vite solve the problems of slow startup and slow HMR in the development of complex and multi-module projects like Webpack?
We compared Vite and Webpack in the development environment in detail, and found that the main differences are as follows:

Webpack Fast
First package and generate the bundle, and then start the development server Start the development server first, use the ESM capability of the new generation browser, directly request the required modules and compile them in real time without packaging
HMR needs to compile all the changed modules and related dependencies For HMR, you only need to ask the browser to re-request the module, and at the same time use the browser's cache (source code module negotiation cache, relying on module strong cache) to optimize the request
efficient use of memory -

Therefore, for the problem of slow startup in the development environment:

  • The cold start of the Vite development environment does not need to be packaged , does not need to analyze the dependencies between modules, and does not need to be compiled before starting the development server. It will also use esbuild to pre-build when starting .
  • After Webpack starts, it will do a lot of things. It will go through a long compilation and packaging chain. From the entrance, it needs to gradually go through syntax analysis, dependency collection, code translation, packaging and merging, code optimization, and finally compile the high-version, discrete source code. Packaged into a low-version, high-compatibility product code, which is full of CPU and IO operations, and there must be performance problems when Node is running.

Slow for HMR:

  • Even with only small changes, Webpack still needs to build a complete module dependency graph and perform transformations according to the dependency graph.
  • However, Vite uses ESM and browser caching technology , and the update speed has nothing to do with the complexity of the project.
    • It can be seen that for non-packaged build tools such as Snowpack and Vite, only two servers need to be started when the development environment is started, one for page loading and one for HMR's Websocket.
    • When the browser sends a native ESM request, the server only needs to compile the current file and return it to the browser after receiving the request, without managing dependencies.

image.png

Easy to use, out of the box
Compared with Webpack, which requires a lot of configuration on entry, loader, plugin, etc., the use of Vite can be described as quite simple.
Just execute the initialization command, you can get a preset development environment, and get a bunch of functions out of the box, including: CSS preprocessing, html preprocessing, asynchronous loading, subpackaging, compression, HMR, etc.
The complexity of its use is between Parcel and Webpack, but only a few configuration items and plugin interfaces are exposed. It will neither be inflexible in configuration like Parcel, nor need to understand the huge loader and plugin ecology like Webpack. Moderate, moderate complexity.

plug-in

Vite can be extended with plugins, thanks to Rollup's excellent plugin interface design and some extra options unique to Vite. Plug-ins make the functions of vite more powerful and perfect.

Configure the plugin:

// vite.config.js
import legacy from '@vitejs/plugin-legacy' // 插件
import {
    
     defineConfig } from 'vite'

export default defineConfig({
    
    
  plugins: [
    legacy({
    
    
      targets: ['defaults', 'not IE 11']
    })
  ]
})

vite plugin

Find plug-ins:
There are many plug-ins available in the community, you can find and choose to use them yourself.
plugin list

vite.config.js

vite.config.js

vite support for vue

vite provides first priority support for vue through plugins:

  • Vue 3 single file component support: @vitejs/plugin-vue
  • Vue 3 JSX 支持:@vitejs/plugin-vue-jsx
  • Vue 2 support: underfin/vite-plugin-vue2

Install:npm install @vitejs/plugin-vue -D

Configure the plugin:

// vite.config.js
import vue from '@vitejs/plugin-vue'

export default {
    
    
  plugins: [vue()]
}

vite scaffolding

In development, it is impossible for us to use vite to build all projects from scratch, such as a react project and a Vue project. At this time, vite also provided us with corresponding scaffolding tools.

So Vite actually has two tools:

  • vite: It is equivalent to a component tool, similar to webpack and rollup;
  • @vitejs/create-app:类似 vue-cli、create-react-app;

Create a project with scaffolding:

  • Install scaffolding:npm install @vitejs/create-app -g
  • use:create-app 项目名称

After filling in the name, you can choose the project you want to create, such as vue or react, etc.

The official website provides a convenient way to create projects, which actually automatically completes the installation and use of scaffolding.

  • npm create vite@latest

After filling in the project name, you can choose the project framework.

For vue projects, you can use npm init vue@latestCreate directly.
It is equivalent to further automatically completing the above steps, and the real son is really different.

Guess you like

Origin blog.csdn.net/qq_43220213/article/details/129607396