The author:maxin, shall not be reproduced without authorization.
Introduction to the
Vite is pronounced [veet], which means light and light in French
The development environment starts local services through KOA, and the production environment is built through Rollup packaging
The characteristics of
- The startup time of the dev server does not exceed 300ms
- Module hot replacement (HMR) updates do not exceed 100ms
- Support TS/JSX conversion through ESbuild
- According to the need to load
esbuild
Esbuild, which is written with Golang at the bottom, has a distinct advantage over the packaging speed of traditional Web build tools. Compiling Typescript is much faster than official TSC
Contrast the vue – cli
With vuE3 and 10 components, Vite has a significant improvement in development server startup time compared to VuE-CLI
Dev-server for traditional packaging tools
- Before running locally, you need to load all the module files and export the bundle to display the page
- This includes parsing the import/export relationships for each file
- Sort, rewrite, and associate modules
- The larger the application, the slower the startup of development services
- Code segmentation is only for production builds
Dev-server based on browser ES Module
<script type="module">
- The browser can parse the ES Module import and send an HTTP request
- Dev Server intercepts the browser request for the module and returns the processed result
<script type="module">
Features of ES Module: - Module code is executed only after loading
- Modules that reference the same JS are loaded only once
- Modules are singletons
- Modules can request that other modules be loaded
- Support for circular dependencies
- By default, it is executed in strict mode
- The global namespace is not shared
- The module’s top-level value for this is undefined
- Module var declarations are not added to Windows
The directory structure
$ tree -L 3 -I 'node_modules'.. / SRC/SRC ├ ─ ─ the client# Client run code, mainly client socket communication and HMR related│ ├── client. Ts │ ├── env.d.ts │ ├── tsconfig.json │ ├─ vuejsxcompat.ts │ ├─ hmrPayload# HMR type definition└ ─ ─ the node# Server run code├ ─ ─ the buildThe # vite build command runs the code│ │ ├ ─ ─ buildPluginAsset. Ts ├ ─ ─ buildPluginCss. Ts │ ├ ─ ─ buildPluginEsbuild. Ts │ ├ ─ ─ buildPluginHtml. Ts │ ├ ─ ─ Exercises │ ├── Exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises │ ├─ exercises ├── cli.ts ├─ Config.ts ├─ EsBuildService.ts# esbuild├ ─ ─ index. Ts ├ ─ ─ optimizer# preliminary optimization│ ├── index.htm │ ├── index.htm │ ├── index.htm │ ├── index.htm │ ├── index.htm │ ├── html.htm# Module loading logic├ ─ ─ server# Some middleware used by koA services│ ├── index. Ts │ ├─ ├─ Pluginassets. Ts │ ├─ ├─ Plugincs.ts# Handle CSS and other CSS preprocessor files│ ├── Pluginenv.ts │ ├─ Pluginesbuild. Ts │ ├─ Pluginhmr.ts# Server hot module replacement related│ │ ├ ─ ─ serverPluginHtml. Ts ├ ─ ─ serverPluginJson. Ts │ ├ ─ ─ serverPluginModuleResolve. Ts/@modules/:id│ │ ├ ─ ─ serverPluginModuleRewrite. Ts ├ ─ ─ serverPluginProxy. Ts │ ├ ─ ─ serverPluginServeStatic. Ts# KoA Static server│ ├─ Heavy Metal Guitar School │ ├─ Heavy Metal Guitar School# process.vue files│ ├── ├─ ch.htm │ ├─ ├─ ch.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm │ ├─ html.htm ├── open browser.ts ├── pathutils.ts ├─ Exercises ├── bases.d.t s ├─ transformutis.tsCopy the code
What did Vite do?
$ vite
- Execute the js corresponding to the bin field of package.json
- createServer
- Initialize koA, watcher, and resolver
- Read the configuration and merge it into the CONTEXT of KOA
- Use a bunch of plugins the way Koa Middlewares does
- Pre-optimize dependencies module files in user projects
Koa middleware
The pattern of koA middleware is used in Vite to handle the different types of files requested. The execution order of the middleware is similar to the onion model shown below
Let’s do a simple example
The execution sequence is as follows:
// First layer of onion - start // Second layer of onion - start // Third layer of onion - start // Third layer of onion - End // Second layer of onion - end // GET / -2ms // First layer of onion - End // First layer of onion - startCopy the code
Request to intercept
- Koa middleware used in Vite
- each
plugin
It’s all a function - Use one or more middleware after execution
- Resource files are parsed and rewritten at request and response time
- Returns a file to the browser that can be executed directly
If the path after import does not start with.,./,.. /, browser does not know how to do?
When accessed by the browser, the path prefix has been processed to /, /@module/:id
open
--debug
Pattern, as you can seevite:rewrite
Handle path overrides
ModuleRewritePlugin does:
- Intercept js files, including *.vue files
<template>
and<script>
- Convert a file through a readable stream into string content and read it
- Use what esbuild provides
es-module-lexer
Lexical analysis - use
magic-string
To replace the unrecognized path in import- Import vue -> @module/vue.js
- / app. vue -> / SRC/app.vue
- The rewritten string is spelled on ctx.body and returned to the next middleware
- The cx. Path and rewritten file are spliced as the rewriteCache key, and the file is cached as the value
- The rewritten path intercepts the request to the server again
- The next time path+file is unchanged, return file directly
- RewriteCache is
lru-cache
The generated Map-like data structure
RewriteImports method
ResolveImport method
Parsing node_modules
ModuleResolvePlugin does:
- The middleware intercepts cx. Path starting with /@modules/
- If the user project dependencies do not have vue, use @vue in vite dependencies
- If the moduleIdToFileMap has a file path corresponding to the ID, read and return the file
- If the pre-optimized directory node_modules/.vite_opt_cache has an ID, read and return the file
- If none, parse the path to the module property of package.json in the module ID from node_modules, read and return the file
*. Vue file?
- through
vuePlugin
Middleware to parse processing - use
@vue/compiler-sfc
Parse the vue file, rewrite it as a new script and export it as an ES Module - The browser parses and asynchronously requests the request processing template with the query parameter again
- use
@vue/compiler-dom
Compile and export the render function to handle the style - Hot update updateStyle and export THE CSS content as JSON strings
Processed style file
The processed template file
The parsed result can be used directly in the createApp method
vite.config.js
The vite documentation has not yet determined how to configure the config file, but can we see from the code
It includes proxy, configureServer, and so on
HMR
When request.path is /vite/client, request the corresponding client code, create a WebSocket service in the client and establish a connection with the server, use the chokidar library to create watcher instance, listen for file changes. Different messages trigger events for instant hot module replacement in the browser
Some optimization
Pre-tuning before starting services
Before starting the service, the NPM dependency of the user project is pre-optimized to be cached in the.vite_opt_cache directory under node_module. There is no import in these JS files, so there is no need to make multiple requests. Use HTTP caching to speed up the load of modules reading from node_modules
Run the vite command to install the NPM package without restarting the service.
Start the server first, then install Lodash-es, skip the pre-optimization, and observe the network for more than 600 requests
Lodash-es was installed before starting the server, and the number of requests was significantly reduced after the pre-optimization
The ctx.read method reads cached files from memory
The node_modules module is parsed for the first time and cached in memory instead of being read from disk each time
http2/https
Executing vite — HTTPS turns on the HTTP2 protocol, allowing multiple requests to be completed concurrently over a TCP connection
conclusion
Vite imports and exports modules in the browser by means of export import, and realizes on-demand loading at the same time. Vite is highly dependent on the Module script feature. At present, it is still in rc version, the project is still in rapid iteration, you can play first.