Introduction to Vite
History and Goals of Vite
Vite is a frontend build tool created by Evan You, the author of Vue.js, and was first introduced in 2020. Its name, derived from the Italian word for “fast,” reflects its primary goal: delivering an exceptionally fast development experience. Vite leverages modern browsers’ native ES module support to achieve rapid startup times and efficient Hot Module Replacement (HMR).
Comparison with Webpack and Other Build Tools
Vite differs significantly from traditional build tools like Webpack in several ways:
- Development Server Startup Speed: Vite uses the browser’s ES module loading mechanism, eliminating the need for a full build during development, resulting in extremely fast startup times. In contrast, Webpack requires building the entire project on startup, which can be slower even with caching.
- Hot Module Replacement (HMR): Vite’s HMR is highly efficient, reloading only the modified modules without rebuilding the entire dependency tree, significantly speeding up development iterations.
- On-Demand Compilation: In development mode, Vite compiles and bundles only the modified modules, not the entire project, further reducing build times.
- ES Module Preloading: Vite leverages the browser’s
<script type="module">tag, allowing direct module imports in development without additional bundling steps.
Core Features of Vite
Vite’s core features focus on enhancing development efficiency and experience:
- Fast Hot Updates: Vite’s HMR completes module updates in milliseconds, enabling developers to see code changes almost instantly without page refreshes.
- ES Module Preloading: By utilizing the browser’s native ES module loading, Vite allows direct module imports in development without complex bundling configurations.
- On-Demand Compilation: Vite compiles and bundles only modified modules in development mode, significantly reducing build times.
Detailed Learning Tutorial
1. Installing Vite
npm create vite@latest
# Follow the prompts to proceed!Creating a Vite Project
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue
# pnpm
pnpm create vite my-vue-app --template vue2. Step-by-Step Code Analysis
Consider a simple Vue component:
<!-- src/components/HelloWorld.vue -->
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vite!'
};
}
};
</script>In Vite, you can directly reference this component in an HTML file:
<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>In main.js:
// src/main.js
import HelloWorld from './components/HelloWorld.vue';
const app = document.querySelector('#app');
app.innerHTML = `<app-hello-world></app-hello-world>`;In this example, Vite automatically resolves ES module imports in main.js and converts them into a browser-compatible format when the development server starts.
3. Performance Optimization
While Vite offers excellent performance in development, it performs a full build process in production, including code splitting, compression, and optimization to generate production-ready static assets.
// vite.config.js
export default {
build: {
rollupOptions: {
// Custom Rollup configuration
},
terserOptions: {
// Terser compression options
},
// Additional build options...
}
};Setting Up the Environment
Installing Node.js and npm/yarn
Vite is a Node.js-based build tool, so you must first ensure Node.js is installed in your development environment. Node.js includes npm (Node Package Manager) for managing packages and dependencies. Yarn, another popular package manager, offers faster installation and more stable dependency management.
Installing Node.js
Visit the Node.js official website, download the installer for your operating system, and follow the prompts to complete the installation.
Installing Yarn (Optional)
If you prefer Yarn, install it with the following command:
npm install -g yarnInitializing a Vite Project
Vite provides the create-vite scaffolding tool for quickly setting up projects. Alternatively, you can manually configure a Vite project, though this requires a deeper understanding and custom setup.
Initializing a Project with create-vite
# Install create-vite globally
npm install -g create-vite
# Create a new project
create-vite my-vite-project
# Navigate to the project directory
cd my-vite-project
# Install project dependencies
npm installcreate-vite will prompt you with questions about the project, such as the framework (e.g., Vue, React) and whether to use TypeScript. Select options based on your needs.
Manually Configuring a Vite Project
If you prefer manual configuration, follow these steps:
Create a Project Directory:
mkdir my-vite-project
cd my-vite-projectInitialize an npm Project:
npm init -yInstall Vite:
npm install vite --save-devCreate vite.config.js:
// vite.config.js
import { defineConfig } from 'vite';
export default defineConfig({
base: './',
server: {
port: 3000,
},
build: {
outDir: 'dist',
assetsDir: 'assets',
},
});Create Project Structure:
my-vite-project/
├── public/
│ └── index.html
├── src/
│ └── main.js
├── vite.config.js
└── package.jsonEdit index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>Edit main.js:
// src/main.js
console.log('Hello, Vite!');Running the Vite Development Server
Whether using create-vite or manual configuration, start the Vite development server with:
npm run devThis launches a development server, typically accessible at http://localhost:3000. Open this URL in a browser to see the output: “Hello, Vite!”.
vite.config.js:
base: Sets the base path for the project.server: Configures the development server port.build: Specifies the output directory and static assets directory.
index.html:
- Contains the basic HTML structure.
- Imports
main.jsas the module entry point.
main.js:
- A simple console log to verify Vite functionality.
Project Structure
index.html as the Entry File
index.html is the root HTML file of a Vite project, typically located in the root or public directory. It serves as the application’s entry point, responsible for loading the main script file. In Vite, index.html generally includes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<!-- Vite will inject your script here -->
<script type="module" src="/src/main.js"></script>
</body>
</html>The key element is the <script type="module"> tag, which indicates an ES module. Vite injects the application’s entry script here.
main.js or main.ts as the Application Entry Script
main.js or main.ts (if using TypeScript) is the main entry script, typically located in the src directory. This file initializes the application, importing other modules, setting up frameworks or libraries, and configuring routing.
// src/main.js
import App from './App.vue';
import { createApp } from 'vue';
const app = createApp(App);
app.mount('#app');In this example, we use the Vue.js framework, where main.js imports the root component App.vue and uses Vue’s createApp function to start the application.
Organization of the public and src Directories
- public Directory: Stores static assets like fonts, images, and non-modular JS/CSS files. Vite does not transform files in the
publicdirectory but copies them directly to the build output directory.
<!-- public/index.html -->
<link rel="stylesheet" href="styles.css">- src Directory: Contains the application’s source code, including components, modules, and stylesheets. Vite transforms and bundles files in the
srcdirectory.
<!-- src/App.vue -->
<template>
<h1>Hello Vite!</h1>
</template>
<script>
export default {
name: 'App',
};
</script>
<style scoped>
h1 {
color: red;
}
</style>Example Project Structure
A typical Vite project structure looks like this:
my-vite-project/
├── node_modules/
├── public/
│ ├── favicon.ico
│ ├── index.html
│ └── styles.css
├── src/
│ ├── App.vue
│ ├── components/
│ │ └── HelloWorld.vue
│ ├── main.js
│ ├── router/
│ │ └── index.js
│ └── store/
│ └── index.js
├── .gitignore
├── package.json
├── package-lock.json
├── README.md
├── vite.config.js
└── yarn.locknode_modules/: Stores project dependencies.public/: Contains static assets.src/: Holds source code.vite.config.js: Vite configuration file.package.json: Project dependencies and scripts..gitignore: List of files ignored by Git.
Code Analysis
index.html:
- Defines the basic HTML structure.
- Imports
main.jsas the module entry point.
src/main.js:
- Imports the root component.
- Uses framework APIs (e.g., Vue’s
createApp) to start the application.
src/App.vue:
- Template, script, and styles for a Vue component.
src/components/HelloWorld.vue:
- Example child component.
src/router/index.js:
- Routing configuration, if using libraries like Vue Router.
src/store/index.js:
- State management, if using libraries like Vuex.
Development Workflow
Real-Time Hot Module Replacement (HMR)
Hot Module Replacement (HMR) is a standout feature of Vite, allowing developers to see code changes without refreshing the page. This significantly reduces wait times, making it invaluable for rapid iteration and debugging.
In Vite, HMR is enabled out of the box. When you modify a module (e.g., a Vue component, stylesheet, or script), Vite detects the change and updates only the affected parts without reloading the entire page.
// Before modification
console.log('Hello, Vite!');
// After modification
console.log('Hello, updated Vite!');After modifying the code, you’ll see the updated console output without needing to refresh the page.
Support for TypeScript and Vue
Vite provides excellent support for TypeScript and Vue, making it easy to use these technologies in projects.
TypeScript
When initializing a project with create-vite, you can opt for TypeScript, which generates .ts or .tsx files and a tsconfig.json configuration file.
// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.mount('#app');Vue
Vite integrates seamlessly with Vue, allowing you to use .vue single-file components without additional configuration. Vite handles the compilation and optimization of Vue components automatically.
<!-- src/App.vue -->
<template>
<div>{{ message }}</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return {
message: 'Hello, Vite!',
};
},
});
</script>Using CSS and Preprocessors
Vite supports CSS preprocessors like Sass, Less, and Stylus. Install the relevant preprocessor package and use the corresponding file extension.
Installing a Preprocessor
For Sass:
npm install sass --save-devUsing a Preprocessor
Create a .scss file in the src directory:
// src/styles/main.scss
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}Importing the Preprocessor
In a component or script:
<!-- src/App.vue -->
<style lang="scss">
@import './styles/main.scss';
</style>Or in main.js:
// src/main.js
import './styles/main.scss';Code Analysis
Real-Time HMR:
- When code is modified, Vite detects changes and updates only the affected parts, avoiding page refreshes.
TypeScript Support:
- Uses
.tsor.tsxfiles, with Vite handling TypeScript compilation. - Supports TypeScript in Vue components via
<script lang="ts">.
Vue Integration:
- Directly uses
.vuesingle-file components, with Vite managing compilation and optimization.
CSS Preprocessors:
- Install preprocessor packages like
sass. - Use
.scss,.less, or.stylfile extensions. - Import preprocessor files in components or scripts.
Features
Core Features
Fast Startup and Hot Module Replacement (HMR):
- Vite leverages the browser’s native ES module loading, enabling near-instant project startup in development without pre-building.
- HMR updates modules in real-time without page refreshes, boosting development efficiency.
On-Demand Compilation:
- In development mode, Vite compiles and bundles only modified modules, significantly reducing build times.
ES Module Preloading:
- Uses the browser’s
<script type="module">tag for direct module imports, simplifying the development process without additional bundling.
Seamless Integration with TypeScript, Vue, React, and Other Frameworks:
- Vite integrates deeply with popular frontend frameworks and languages like TypeScript, Vue, and React, offering out-of-the-box support.
CSS Preprocessor Support:
- Supports Sass, Less, Stylus, and other preprocessors without additional configuration.
Build Optimization:
- In production, Vite performs comprehensive code splitting, compression, and optimization to generate efficient, compact static assets.
Configuration Options
The Vite configuration file, vite.config.js (or vite.config.ts), offers extensive options for customizing build behavior and optimizing projects.
base:
- Sets the base path for URLs in the build output.
plugins:
- Plugin system for extending Vite’s functionality, such as code analysis and lazy loading.
server:
- Configures the development server, including port and proxy settings.
build:
- Build-related settings, such as output directory, compression options, and code-splitting strategies.
resolve:
- Rules for resolving module IDs, including aliases and conditional compilation.
optimizeDeps:
- Dependency optimization settings for pre-building and optimizing dependencies.
Plugin System
Vite’s plugin system allows developers to extend and customize the build process. Plugins can handle code transformation, asset processing, and performance optimization.
load and transform Hooks:
loadretrieves file contents, andtransformmodifies file contents.
buildStart and buildEnd:
- Hooks triggered at the start and end of the build process for initialization or cleanup tasks.
configureServer:
- Configures development server behavior, such as adding middleware or modifying request handling logic.
Optimizing Projects with Vite
Using ES Module Syntax:
- Leverage ES module import/export syntax for modular, maintainable, and refactorable code.
Adopting TypeScript:
- TypeScript provides static type checking, catching errors early and improving code quality.
Leveraging HMR:
- Use HMR during development to instantly see code changes, speeding up iterations.
Optimizing Build Configuration:
- Adjust
vite.config.jssettings, such as code-splitting strategies and compression options, to optimize build output.
Using Plugins:
- Select appropriate plugins based on project needs to enhance functionality, such as code analysis or performance monitoring.
Continuous Integration/Continuous Deployment (CI/CD):
- Integrate Vite into CI/CD pipelines to automate building and deployment, improving development efficiency and project reliability.
Code Analysis
Below is an example of a simple project using Vite, Vue, and TypeScript:
Initializing the Project
Use the create-vite scaffold to create the project:
npx create-vite my-vite-project --template vue-tsEditing src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.mount('#app');Creating a Vue Component (src/App.vue)
<template>
<div>{{ message }}</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
data() {
return {
message: 'Hello, Vite!',
};
},
});
</script>Configuring Vite (vite.config.js)
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
build: {
outDir: 'dist',
assetsDir: 'static',
rollupOptions: {
input: 'index.html',
},
},
});Running the Project
npm run dev



