Vite is a front-end builder that is known in the front-end world for its fast development server and production-optimized packager. For today's content, it is important to harp on Vite's key capabilities, and the following is a breakdown of Vite's core components, as well as use cases:
-
principle analysis:
- Vite takes advantage of the fact that modern browsers are not familiar with the
ESModule
syntax support, which is not packaged and compiled in the development environment, but by launching the localdevServer
to provide the service, which significantly improves startup speed . - During development, Vite loads the modules needed for a page on demand, rather than compiling the entire project at once.
- Vite Usage
esbuild
Performs dependency pre-builds, converts multiple modular specifications to ESM, and reduces network requests . - Vite optimizes performance with HTTP caching and filesystem caching, using the
es-module-lexer
cap (a poem)magic-string
Rewrite the module path .
- Vite takes advantage of the fact that modern browsers are not familiar with the
-
source code implementation:
- Vite's source code is divided into two main parts: the client code handles WebSocket messages and the server code handles code construction and module requests.
- Vite's server side uses the Koa framework to serve modules by intercepting HTTP requests.
-
Tips for use:
- Take advantage of Vite's rapid development experience to get projects off the ground and preview changes in real time.
- Because Vite supports native ESM, it is possible to run unpackaged code directly in the browser, simplifying the development process.
- Vite is easy to configure and usually requires only one configuration file to build and deploy a project.
- Vite supports multiple front-end frameworks and languages, allowing flexibility in choosing a technology stack .
-
Advantages of Vite over Webpack:
- Vite offers faster cold start and hot module replacement.
- Vite supports native ESM without additional translation and packaging steps.
- Vite enables on-demand loading, reducing the cost of building and loading.
- Vite offers easy and zero configuration options to simplify project setup.
Vite's design philosophy is to utilize the power of modern browsers as much as possible, reducing unnecessary packaging operations and thus increasing development efficiency. In production environments, Vite is packaged using Rollup, ensuring optimization and performance of the final product.
Vite's core component functionality consists of the following main areas:
-
Development Server (Dev Server):
- Vite provides a fast development server that utilizes HTTP/2 and ES Modules (ESM) to provide services for fast module loading and hot updates.
-
Compile on Demand:
- Vite compiles requested modules on-demand in development mode, rather than compiling the entire project at once, which greatly improves responsiveness during development.
-
dependency pre-build:
- Vite Usage
esbuild
Pre-built dependencies convert modular specifications such as CommonJS, UMD, etc. to ESM, reducing the number of network requests and improving performance.
- Vite Usage
-
Heat Module Replacement (HMR):
- Vite implements an efficient hot-module replacement mechanism, so that when the source code changes, only the changed part is replaced, without reloading the entire page.
-
caching mechanism:
- Vite utilizes HTTP caching and file system caching to improve performance, strong caching for infrequently changing dependencies, and negotiated caching for source code parts.
-
Module path rewriting:
- Vite Usage
es-module-lexer
cap (a poem)magic-string
to parse and rewrite module paths to accommodate the browser's module loading mechanism.
- Vite Usage
-
Build Optimization:
- In production mode, Vite uses Rollup or other build tools to package the application and generate optimized static resources.
-
plug-in system:
- Vite supports plugin extensions that allow developers to customize the build process through plugins, such as adding support for specific types of files.
V will introduce each of these core functions and explain them with case studies.
1. Development server (Dev Server)
Dev Server is one of the core components of Vite, which provides fast module loading and hot updating during the development process. The following is a simple example and analysis of the Dev Server:
Let's look at a case study.
Let's say we have a simple Vue 3 project and we want to use Vite to start the development server. Here is the directory structure and key files of the project:
/my-vue-app
|-- node_modules
|-- public
| |--
|-- src
| |--
| |--
|--
|--
-
(
public/
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vite Vue App</title>
</head>
<body>
<div ></div>
<script type="module" src="/src/"></script>
</body>
</html>
-
(
src/
):
import { createApp } from 'vue';
import App from './';
const app = createApp(App);
('#app');
-
(
src/
):
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script setup>
const message = 'Hello Vite!';
</script>
-
(
):
//
= {
// Configuration options...
};
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
This command executes the defined in
"dev"
script that starts the development server using Vite.
Let's get down to brass tacks.
-
service activation:
- When executing the
npm run dev
When you do, Vite starts a local development server.
- When executing the
-
modular service:
- The development server listens for changes to the filesystem and creates a new file system for the
referenced in
type="module"
Scripts provide services.
- The development server listens for changes to the filesystem and creates a new file system for the
-
Load on Demand:
- When the browser requests
/src/
When it does, the Vite server serves up the contents of the file and parses and loads dependent modules on demand (such as the)。
- When the browser requests
-
Hot Updates (HMR):
- in the event that
or other dependencies change, Vite pushes the update to the browser via WebSocket, enabling hot updates without the need to refresh the page.
- in the event that
-
Sourcemap:
- Vite generates a Sourcemap, making it possible to debug the original source code directly in the browser's developer tools, rather than converted code.
-
Separation of development and production:
- Development servers focus on the development experience, while production builds are optimized using Rollup or other configurations to ensure performance in the production environment.
2. On-demand compilation
On-demand compilation is a core feature of Vite that allows developers to compile only those modules that are actually requested during development, rather than the entire project. Below is an example and explanation of on-demand compilation using Vite:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- public/
|-- src/
| |--
| |--
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import App from './';
const app = createApp(App);
('#app');
-
(
src/
):
<template>
<div>
<h1>Home Page</h1>
<button @click="loadComponent">Load Component</button>
</div>
</template>
<script>
import SomeComponent from './';
export default {
methods: {
loadComponent() {
this.$forceUpdate();
this.$ = SomeComponent;
}
}
}
</script>
-
(
src/
):
<template>
<div>
<h2>I'm a lazy-loaded component!</h2>
</div>
</template>
<script>
export default {
name: 'SomeComponent'
}
</script>
-
(
):
//
= {
// Configuration options...
};
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
Compile and parse on demand
-
first time load:
- When you visit the homepage of the app, only the
cap (a poem)
will be loaded and compiled because they are the initial entry points.
- When you visit the homepage of the app, only the
-
Load components on demand:
- Triggered when the user clicks the button
loadComponent
method when thewill be loaded on demand. Since Vite supports ES modules, this component will be loaded through the dynamic
import()
Syntax asynchronous loading.
- Triggered when the user clicks the button
-
Compile the requested module:
- (coll.) fail (a student)
When requested, Vite's development server captures the request, compiles the module, and sends it to the browser.
- (coll.) fail (a student)
-
Hot Updates (HMR):
- in the event that
modified during development, Vite will update the component in the browser via HMR without reloading the entire page.
- in the event that
-
Optimize development experience:
- On-demand compilation reduces initial load time and resource consumption while maintaining rapid module updates and hot-replacement capabilities.
In a nutshell, Vite provides a faster development experience and more efficient resource management by compiling on demand.
3. Reliance on pre-construction
Dependency pre-build is an important feature of Vite that pre-processes project dependencies before the project is started, converting non-ES modules to ES modules to reduce the number of module requests during development and improve performance. Below is an example and explanation of dependency pre-build:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
| |-- some-pkg/
| |--
| |--
|-- src/
| |--
| |--
|--
|--
Contents of the document
-
(
node_modules/some-pkg/
- A CommonJS module).
// CommonJS module (in software)
= function() {
('CommonJS package loaded');
};
-
(
src/
):
import { createApp } from 'vue';
import App from './';
import somePkg from 'some-pkg';
(); // Using pre-built dependencies
const app = createApp(App);
('#app');
-
(
src/
):
<template>
<div>
<h1>App Component</h1>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
-
(
):
//
= {
// Configuration options, e.g. alias @ pointing to src directory
alias: {
'@': '/src',
}, // Other configurations...
// Other configuration...
};
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0",
"some-pkg": "1.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
Dependency Pre-Build Process Explained
-
preconstruction process:
- When Vite starts, it checks the
node_modules
directory and use the dependencies in theesbuild
This high-performance JavaScript packager pre-builds these dependencies.
- When Vite starts, it checks the
-
Conversion module type:
- If the dependency is CommonJS or another non-ES module type, the
esbuild
It will be converted to an ES module so that browsers can access it via theimport
statement is loaded.
- If the dependency is CommonJS or another non-ES module type, the
-
Reduction in the number of requests:
- With pre-builds, Vite can reduce the number of HTTP requests and speed up page loads by combining multiple small dependencies into one large module.
-
Cache Optimization:
- Pre-built dependencies are cached into the
node_modules/.vite
directory so that during development, it is only rebuilt if the dependency changes, otherwise the cache is used directly.
- Pre-built dependencies are cached into the
-
compatibility:
- Pre-builds ensure that dependencies are loaded and executed correctly even in older browser environments that do not support native ES modules.
-
Development server startup:
- Once the pre-build is complete, Vite will launch a development server to serve the source code and pre-build dependencies.
To summarize, Vite significantly improves development efficiency and performance on large projects, while ensuring code compatibility and on-demand loading of modules.
4. Heat Module Replacement (HMR)
Hot Module Replacement (HMR) is a feature provided by Vite during the development process that allows developers to replace, add or remove modules without refreshing the entire browser page. Here is the HMR example and analysis, take a look:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- public/
|-- src/
| |--
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import Button from './';
const app = createApp();
('button-component', Button);
('#app');
-
(
src/
):
<template>
<button @click="count++">Count is: {{ count }}</button>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
</script>
-
(
public/
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vite HMR Demo</title>
</head>
<body>
<div >
<button-component></button-component>
</div>
<script type="module" src="/src/"></script>
</body>
</html>
-
(
):
//
= {
// HMR is enabled by default, no additional configuration is required
};
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
HMR Process Analysis
-
Development server startup:
- When you start Vite, the development server starts and automatically enables the HMR feature.
-
Modifying the Button Component:
- Let's say you're in the process of developing a modified
templates or scripts.
- Let's say you're in the process of developing a modified
-
HMR Replacement Module:
- After saving the file, Vite compiles the modified
component and use HMR to update the corresponding module in the browser without reloading the entire page.
- After saving the file, Vite compiles the modified
-
maintenance:
- Due to the nature of the HMR
hit the nail on the head
count
The state will remain the same, even if the component is reloaded. The user will see the count displayed on the button continue to increase after the click without the page refreshing.
- Due to the nature of the HMR
-
Browser Developer Tools:
- In your browser's developer tools, you can see that the web request is only for the modified module, not the entire resource.
To summarize, we can see that Vite's HMR feature makes development more efficient, allowing developers to quickly iterate on components while maintaining application state and user experience.
5. Caching mechanisms
There are two main aspects of the caching mechanism in Vite:HTTP Cachecap (a poem)file system cache. The following is a case study and analysis of the caching mechanism:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- public/
|-- src/
| |--
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import App from './';
createApp(App).mount('#app');
-
(
src/
):
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vite!'
};
}
}
</script>
-
(
public/
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vite Cache Demo</title>
</head>
<body>
<div ></div>
<script type="module" src="/src/"></script>
</body>
</html>
-
(
):
//
= {
// Configuration options...
};
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
Caching Mechanisms Explained
-
HTTP Cache:
- Vite sets HTTP cache headers for static resources. For resources that change infrequently (such as pre-built dependencies), Vite uses the
Cache-Control
response header that specifies that the resource can be cached by the browser.
- Vite sets HTTP cache headers for static resources. For resources that change infrequently (such as pre-built dependencies), Vite uses the
-
file system cache:
- Vite will be in
node_modules/.vite
directory to cache pre-built dependencies. When there are no changes, Vite reads the dependencies directly from this cache, avoiding duplicate builds.
- Vite will be in
-
sample operation (computing):
- Suppose you modify the
hit the nail on the head
message
Data. After saving the file, Vite triggers an HMR update, but does not rebuild the entire project's dependencies.
- Suppose you modify the
-
Browser Cache Utilization:
- When you access resources provided by the development server (such as the
), the browser caches these resources according to the caching instructions in the HTTP response header. The next time the same resource is accessed, if it has not been updated, the browser uses the local cache instead of re-downloading it from the server.
- When you access resources provided by the development server (such as the
-
negotiation cache:
- For source files, Vite uses HTTP negotiated caching (e.g., the
ETag
maybeLast-Modified
). Vite updates these tags when there are updates to the source file, and the browser uses these tags to determine whether it needs to fetch the new resource from the server.
- For source files, Vite uses HTTP negotiated caching (e.g., the
-
Development Experience Optimization:
- Through caching mechanisms, Vite reduces network transfers and duplicate builds during development, improving the responsiveness of the development server and the development experience.
Vite's caching mechanism helps improve development efficiency while reducing unnecessary resource loading and building processes, get it.
6. Module path rewriting
Vite, when processing module paths, needs to set the paths based on the path to a browser-recognizable path. In addition, Vite supports the use of
@
symbols assrc
directory aliases, which is especially common in Vue Single File Components (SFCs). Take a look at this example and parse:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- public/
|-- src/
| |-- components/
| | |--
| |-- views/
| | |--
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import Home from '@/views/';
createApp(Home).mount('#app');
-
(
src/views/
):
<template>
<div>
<h1>Welcome to the Home page</h1>
<my-component />
</div>
</template>
<script>
import MyComponent from '@/components/';
export default {
components: {
MyComponent
}
}
</script>
-
(
src/components/
):
<template>
<div>I'm a component!</div>
</template>
<script>
export default {
name: 'MyComponent'
}
</script>
-
(
):
//
= {
// Set the alias @ to the src directory
alias: {
'@/': '/src/',
'vue': 'vue/dist/'
}
}
-
(
):
{
"scripts": {
"dev": "vite"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0"
}
}
Starting the Development Server
In the project root directory, run the following command to start the development server:
npm run dev
analyze
-
Alias Configuration:
- exist
in which we set the
@
alias points to the project'ssrc
Catalog. This way, we can use the@/views/
Such paths are used instead of relative or absolute paths.
- exist
-
Module requests:
- (coll.) fail (a student)
(indicates passive-voice clauses)
When referenced, the browser sends a request to the Vite development server for the
@/views/
。
- (coll.) fail (a student)
-
path rewrite:
- The Vite server receives the request and, based on the configured alias, sends the
@/views/
Convert to actual file path/src/views/
。
- The Vite server receives the request and, based on the configured alias, sends the
-
Handling single file components:
- Vite Usage
es-module-lexer
to analyzeimport
statement and rewrite the module path according to the browser's support for ES modules.
- Vite Usage
-
service module:
- Vite processes the requested module, and in the case of a Vue single-file component, Vite breaks it down into the
.js
cap (a poem).css
(if any), etc. and serves these modules separately.
- Vite processes the requested module, and in the case of a Vue single-file component, Vite breaks it down into the
-
browser loading:
- The browser loads the module based on the path to the Vite service, and since the path has been converted to one that the browser recognizes, the module loads and executes correctly.
Vite supports aliasing and on-demand loading of single-file components through module path rewriting, which improves development efficiency and ease of modularity management, sort of.
7. Build optimization
Build optimization is a key feature of Vite in production environments, ensuring that final static resources are compressed, segmented and optimized to improve application performance. Below is an example and explanation of build optimization:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- public/
|-- src/
| |--
| |--
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import App from './';
import SomeLib from './SomeLib';
createApp(App).mount('#app');
// Using Library Functions
();
-
(
src/
):
<template>
<div >
<h1>My Vue App</h1>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
-
(
src/
):
export function doSomething() {
('Library function called');
}
-
(
):
//
= {
build: {
// Configure production build options
minify: 'terser', // use terser for code compression
sourcemap: true, // Generate sourcemap files
rollupOptions: {
output: {
manualChunks: {
lib: ['src/'], // package the code into a single chunk
}
}
}
}
}.
-
(
):
{
"scripts": {
"build": "vite build"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"vite": "^2.0.0",
"terser": "^5.0.0"
}
}
Build the project
In the project root directory, run the following command to build the project:
npm run build
Analyze this.
-
Configuring build options:
- exist
We configured the build options, including the code compression tool
terser
and sourcemap generation.
- exist
-
Manual chunking:
- We use
rollupOptions
hit the nail on the headmanualChunks
configure willpackaged into a single chunk, which helps with on-demand loading and caching.
- We use
-
Execute the build:
- (of a computer) run
npm run build
After that, Vite will start the build process and perform code compression, chunking, etc. based on the configuration.
- (of a computer) run
-
Code Compression:
- utilization
terser
Vite compresses JavaScript code, removes extra spaces, comments, and performs some optimizations to reduce file size.
- utilization
-
Generate sourcemap:
- During the build process, Vite generates sourcemap files, which help debug the code in the production environment.
-
Output build results:
- Once the build is complete, Vite will add the
dist
directory to generate optimized static resources, including JavaScript, CSS, and other static resource files.
- Once the build is complete, Vite will add the
-
deployments:
- The build results can be deployed directly to production servers, and due to the optimizations, application loading speed and performance will be improved.
Vite performs build optimizations in production environments, including code compression, manual chunking, sourcemap generation, and more, to ensure application performance and maintainability.
8. Plug-in systems
Vite's plugin system allows developers to extend Vite's functionality, such as adding support for specific types of files, optimizing the build process, and more, take a look:
Project structure
Suppose we have the following project structure:
/my-vue-app
|-- node_modules/
|-- src/
| |--
| |--
| |-- assets/
| |--
|--
|--
Contents of the document
-
(
src/
):
import { createApp } from 'vue';
import App from './';
import './assets/';
createApp(App).mount('#app');
-
(
src/
):
<template>
<div>
<img src="" alt="Image">
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
-
(
):
//
import vue from '@vitejs/plugin-vue';
import path from 'path'; }; import imageTransformPlugin from '.
import imageTransformPlugin from '. /imageTransformPlugin'; // Suppose we create a custom plugin
= {
plugins: [
vue(), // Vite's official Vue plugin for working with Vue single-file components
imageTransformPlugin, // Use the custom plugin to handle image transformations
], // The custom plugin to handle image transformations.
// Other configuration...
};
-
(
):
// Customize the plugin to handle image files
export default {
name: 'image-transform-plugin',
transform(code, id) {
if (('.png')) {
// Assuming we're doing some kind of transformation on the image
const transformedCode = (/.png$/, '-');
return {
code: transformedCode, map: null, // Simplify here.
map: null, // This is simplified here, the plugin should actually generate a sourcemap.
}; }
}
}, }
}; }
-
(
):
{
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"vue": "^3.0.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^2.0.0",
"vite": "^2.0.0"
}
}
Using plug-ins
-
Installation of plug-ins:
- First, we installed the
@vitejs/plugin-vue
This is the official Vite plugin for supporting Vue single-file components.
- First, we installed the
-
Creating custom plug-ins:
- We created a file named
imageTransformPlugin
A custom plug-in to handle the conversion of image files.
- We created a file named
-
Configuring Plug-ins:
- exist
We add these two plugins to the
plugins
array so that Vite applies these plugins at build time.
- exist
-
Running Vite:
- When you run
npm run dev
maybenpm run build
When you do, Vite uses the configured plugins to handle the project resources.
- When you run
process analysis
-
Vue plugin (
@vitejs/plugin-vue
):- This plugin enables Vite to recognize and process
.vue
files, break them down into JavaScript, CSS, and template code, and apply HMR.
- This plugin enables Vite to recognize and process
-
Custom Image Conversion Plugin (
imageTransformPlugin
):- Our custom plugin intercepts messages that start with
.png
The file request at the end is simply "converted" (this is just an example, in reality it may be more complex image processing logic).
- Our custom plugin intercepts messages that start with
-
plug-in hook:
- The Vite plugin system provides a variety of hooks (e.g.
transform
), allowing plugins to intervene and modify the processing logic at different stages of the build process.
- The Vite plugin system provides a variety of hooks (e.g.
-
Application Plug-ins:
- When requesting an image resource, Vite first looks to see if there is a plugin that handles the resource. In our case, the custom plugin intercepts the request and returns the "converted" resource.
The Vite plug-in system allows developers to customize the build process and enhance Vite to fit a variety of development needs.
ultimate
In addition to the above, Vite has official support for Vue 3 and React 17+, allowing developers to develop with these front-end frameworks.Vite has built-in support for TypeScript, which allows you to develop in TypeScript with no additional configuration.Vite handles CSS files and a variety of static resources including images, fonts, etc., and supports CSS preprocessors.Vite generates Sourcemaps, making it easy to debug source code in the browser.Vite supports injecting environment variables during the build process, making configuration more flexible. Vite can generate Sourcemap , developers can easily debug the source code in the browser . Vite supports injecting environment variables during the build process , making the configuration more flexible . If you still know what about the ability of Vite , welcome to V brother point of view , thank you.
Together, these core components make up the power of Vite, making it an efficient, flexible and easy to use front-end building tool, if you have not yet used Vite, then get it.