Location>code7788 >text

Why use Vite Framework? See its core components in detail

Popularity:451 ℃/2024-08-26 13:50:51

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:

  1. principle analysis

    • Vite takes advantage of the fact that modern browsers are not familiar with theESModule 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 Usageesbuild Performs dependency pre-builds, converts multiple modular specifications to ESM, and reduces network requests .
    • Vite optimizes performance with HTTP caching and filesystem caching, using thees-module-lexer cap (a poem)magic-string Rewrite the module path .
  2. 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.
  3. 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 .
  4. 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:

  1. 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.
  2. 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.
  3. dependency pre-build

    • Vite Usageesbuild Pre-built dependencies convert modular specifications such as CommonJS, UMD, etc. to ESM, reducing the number of network requests and improving performance.
  4. 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.
  5. 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.
  6. Module path rewriting

    • Vite Usagees-module-lexer cap (a poem)magic-string to parse and rewrite module paths to accommodate the browser's module loading mechanism.
  7. Build Optimization

    • In production mode, Vite uses Rollup or other build tools to package the application and generate optimized static resources.
  8. 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
|   |-- 
|   |-- 
|-- 
|-- 
  1. (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>
  1. (src/):
   import { createApp } from 'vue';
   import App from './';

   const app = createApp(App);
   ('#app');
  1. (src/):
   <template>
     <div>
       <h1>{{ message }}</h1>
     </div>
   </template>

   <script setup>
   const message = 'Hello Vite!';
   </script>
  1. ():
   //
    = {
     // Configuration options...
   };
  1. ():
   {
     "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.

  1. service activation

    • When executing thenpm run dev When you do, Vite starts a local development server.
  2. modular service

    • The development server listens for changes to the filesystem and creates a new file system for the referenced intype="module" Scripts provide services.
  3. 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)。
  4. 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.
  5. 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.
  6. 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

  1. (src/):
   import { createApp } from 'vue';
   import App from './';

   const app = createApp(App);
   ('#app');
  1. (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>
  1. (src/):
   <template>
     <div>
       <h2>I'm a lazy-loaded component!</h2>
     </div>
   </template>

   <script>
   export default {
     name: 'SomeComponent'
   }
   </script>
  1. ():
   //
    = {
     // Configuration options...
   };
  1. ():
   {
     "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

  1. 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.
  2. Load components on demand

    • Triggered when the user clicks the buttonloadComponent method when the will be loaded on demand. Since Vite supports ES modules, this component will be loaded through the dynamicimport() Syntax asynchronous loading.
  3. 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.
  4. 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.
  5. 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

  1. (node_modules/some-pkg/ - A CommonJS module).
   // CommonJS module (in software)
    = function() {
     ('CommonJS package loaded');
   };
  1. (src/):
   import { createApp } from 'vue';
   import App from './';
   import somePkg from 'some-pkg';

   (); // Using pre-built dependencies

   const app = createApp(App);
   ('#app');
  1. (src/):
   <template>
     <div>
       <h1>App Component</h1>
     </div>
   </template>

   <script>
   export default {
     name: 'App'
   }
   </script>
  1. ():
   //
    = {
     // Configuration options, e.g. alias @ pointing to src directory
     alias: {
       '@': '/src',
     }, // Other configurations...
     // Other configuration...
   };
  1. ():
   {
     "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

  1. preconstruction process

    • When Vite starts, it checks thenode_modules directory and use the dependencies in theesbuild This high-performance JavaScript packager pre-builds these dependencies.
  2. Conversion module type

    • If the dependency is CommonJS or another non-ES module type, theesbuild It will be converted to an ES module so that browsers can access it via theimport statement is loaded.
  3. 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.
  4. Cache Optimization

    • Pre-built dependencies are cached into thenode_modules/.vite directory so that during development, it is only rebuilt if the dependency changes, otherwise the cache is used directly.
  5. compatibility

    • Pre-builds ensure that dependencies are loaded and executed correctly even in older browser environments that do not support native ES modules.
  6. 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

  1. (src/):
   import { createApp } from 'vue';
   import Button from './';

   const app = createApp();
   ('button-component', Button);
   ('#app');
  1. (src/):
   <template>
     <button @click="count++">Count is: {{ count }}</button>
   </template>

   <script setup>
   import { ref } from 'vue';

   const count = ref(0);
   </script>
  1. (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>
  1. ():
   //
    = {
     // HMR is enabled by default, no additional configuration is required
   };
  1. ():
   {
     "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

  1. Development server startup

    • When you start Vite, the development server starts and automatically enables the HMR feature.
  2. Modifying the Button Component

    • Let's say you're in the process of developing a modified templates or scripts.
  3. 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.
  4. maintenance

    • Due to the nature of the HMR hit the nail on the headcount 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.
  5. 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

  1. (src/):
   import { createApp } from 'vue';
   import App from './';

   createApp(App).mount('#app');
  1. (src/):
   <template>
     <div>
       <h1>{{ message }}</h1>
     </div>
   </template>

   <script>
   export default {
     data() {
       return {
         message: 'Hello, Vite!'
       };
     }
   }
   </script>
  1. (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>
  1. ():
   //
    = {
     // Configuration options...
   };
  1. ():
   {
     "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

  1. HTTP Cache

    • Vite sets HTTP cache headers for static resources. For resources that change infrequently (such as pre-built dependencies), Vite uses theCache-Control response header that specifies that the resource can be cached by the browser.
  2. file system cache

    • Vite will be innode_modules/.vite directory to cache pre-built dependencies. When there are no changes, Vite reads the dependencies directly from this cache, avoiding duplicate builds.
  3. sample operation (computing)

    • Suppose you modify the hit the nail on the headmessage Data. After saving the file, Vite triggers an HMR update, but does not rebuild the entire project's dependencies.
  4. 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.
  5. negotiation cache

    • For source files, Vite uses HTTP negotiated caching (e.g., theETag 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.
  6. 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

  1. (src/):
   import { createApp } from 'vue';
   import Home from '@/views/';

   createApp(Home).mount('#app');
  1. (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>
  1. (src/components/):
   <template>
     <div>I'm a component!</div>
   </template>

   <script>
   export default {
     name: 'MyComponent'
   }
   </script>
  1. ():
   //
    = {
     // Set the alias @ to the src directory
     alias: {
       '@/': '/src/',
       'vue': 'vue/dist/'
     }
   }
  1. ():
   {
     "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

  1. 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.
  2. 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/
  3. path rewrite

    • The Vite server receives the request and, based on the configured alias, sends the@/views/ Convert to actual file path/src/views/
  4. Handling single file components

    • Vite Usagees-module-lexer to analyzeimport statement and rewrite the module path according to the browser's support for ES modules.
  5. 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.
  6. 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

  1. (src/):
   import { createApp } from 'vue';
   import App from './';
   import SomeLib from './SomeLib';

   createApp(App).mount('#app');

   // Using Library Functions
   ();
  1. (src/):
   <template>
     <div >
       <h1>My Vue App</h1>
     </div>
   </template>

   <script>
   export default {
     name: 'App'
   }
   </script>
  1. (src/):
   export function doSomething() {
     ('Library function called');
   }
  1. ():
   //
    = {
     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
           }
         }
       }
     }
   }.
  1. ():
   {
     "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.

  1. Configuring build options

    • exist We configured the build options, including the code compression toolterser and sourcemap generation.
  2. Manual chunking

    • We userollupOptions hit the nail on the headmanualChunks configure will packaged into a single chunk, which helps with on-demand loading and caching.
  3. Execute the build

    • (of a computer) runnpm run build After that, Vite will start the build process and perform code compression, chunking, etc. based on the configuration.
  4. Code Compression

    • utilizationterserVite compresses JavaScript code, removes extra spaces, comments, and performs some optimizations to reduce file size.
  5. Generate sourcemap

    • During the build process, Vite generates sourcemap files, which help debug the code in the production environment.
  6. Output build results

    • Once the build is complete, Vite will add thedist directory to generate optimized static resources, including JavaScript, CSS, and other static resource files.
  7. 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

  1. (src/):
   import { createApp } from 'vue';
   import App from './';
   import './assets/';

   createApp(App).mount('#app');
  1. (src/):
   <template>
     <div>
       <img src="" alt="Image">
     </div>
   </template>

   <script>
   export default {
     name: 'App'
   }
   </script>
  1. ():
   //
   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...
   };
  1. ():
   // 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.
         }; }
       }
     }, }
   }; }
  1. ():
   {
     "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

  1. Installation of plug-ins

    • First, we installed the@vitejs/plugin-vueThis is the official Vite plugin for supporting Vue single-file components.
  2. Creating custom plug-ins

    • We created a file namedimageTransformPlugin A custom plug-in to handle the conversion of image files.
  3. Configuring Plug-ins

    • exist We add these two plugins to theplugins array so that Vite applies these plugins at build time.
  4. Running Vite

    • When you runnpm run dev maybenpm run build When you do, Vite uses the configured plugins to handle the project resources.

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.
  • 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).
  • 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.
  • 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.