Project initialization and template selection
Project Configuration and Basic Usage
Vite.js is a modern front-end build tool that leverages native browser ES module support to enable fast development server startup and hot updates. Compared to traditional bundling tools, Vite in the development environment requires almost no waiting for the bundling process, directly compiling source files on demand, significantly improving the development experience. In the production environment, it uses Rollup for efficient bundling.
Project Initialization and Template Selection
Creating a new project with Vite is very simple, and the official provides multiple methods. The most common way is to initialize the project via npm or yarn:
npm create vite@latest
# or
yarn create vite
After executing the command, you will enter an interactive command-line interface where you need to sequentially select the project name, framework, and variant. Vite supports multiple mainstream front-end frameworks:
- Vanilla - Pure JavaScript/TypeScript project
- Vue - Supports Vue 2 and Vue 3
- React - Supports React and React + TypeScript
- Preact - Lightweight React alternative
- Lit - Web Components framework
- Svelte - Compiled front-end framework
- Solid - Reactive JavaScript library
For example, to create a Vue 3 + TypeScript project:
npm create vite@latest my-vue-app --template vue-ts
After creation, the project directory structure typically looks like this:
my-vue-app/
├── node_modules/
├── public/
├── src/
│ ├── assets/
│ ├── components/
│ ├── App.vue
│ ├── main.ts
│ ├── style.css
│ └── vite-env.d.ts
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts
Configuration File Details
The core configuration file for Vite is vite.config.ts
(or .js
), which exports a configuration object. A basic configuration example is as follows:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true
},
build: {
outDir: 'dist',
assetsDir: 'assets'
}
})
Common configuration items include:
plugins
: Configure the Vite plugins to useserver
: Development server optionsport
: Specify the port numberopen
: Whether to automatically open the browserproxy
: Configure proxies
build
: Production build optionsoutDir
: Output directoryassetsDir
: Static assets directoryminify
: Whether to minify the code
Development Server and Hot Updates
Starting the development server is very simple:
npm run dev
# or
yarn dev
Vite's development server has the following features:
- Instant Startup - No need to wait for bundling; it is almost immediate
- On-Demand Compilation - Only compiles the modules needed for the current page
- Hot Module Replacement (HMR) - Updates modules while preserving the application state
For example, when modifying a Vue component, only that component will be reloaded without refreshing the entire page.
Environment Variables and Modes
Vite uses dotenv to load environment variables from .env
files. The following files can be created in the project root directory:
.env
: Loaded in all cases.env.local
: Local overrides, ignored by git.env.[mode]
: Environment variables for specific modes.env.[mode].local
: Local overrides for specific modes
Variable names must start with VITE_
to be accessible on the client side:
VITE_API_URL=https://api.example.com
VITE_DEBUG=true
In the code, they can be accessed via import.meta.env
:
console.log(import.meta.env.VITE_API_URL)
Static Asset Handling
Vite provides multiple ways to handle static assets:
- Direct Import - Returns the resolved URL
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
-
Public Directory - Files under
public
are directly copied to the root directory -
JSON Import - JSON files can be directly imported
import pkg from './package.json'
- Glob Import - Batch import modules
const modules = import.meta.glob('./dir/*.js')
CSS and Preprocessor Support
Vite has built-in support for CSS and various CSS preprocessors, requiring no additional configuration:
// Directly import CSS
import './style.css'
// Import Sass
import './style.scss'
// Import Less
import './style.less'
Supports CSS Modules by adding .module
to the filename:
import styles from './module.module.css'
function Component() {
return <div className={styles.error}>Error Message</div>
}
Build Optimization
Vite automatically performs multiple optimizations during production builds:
- Code Splitting - Automatically splits code chunks
- Async Loading - Dynamically imported modules are split into separate chunks
- Asset Inlining - Small files are automatically converted to base64
- Preload Directives - Automatically generates
<link rel="modulepreload">
Further optimizations can be configured:
build: {
rollupOptions: {
output: {
manualChunks: {
'vendor': ['vue', 'vue-router', 'pinia']
}
}
}
}
Plugin System
Vite's plugin system is compatible with Rollup plugins and has its own unique hooks. Common official plugins include:
@vitejs/plugin-vue
: Vue support@vitejs/plugin-react
: React support@vitejs/plugin-legacy
: Legacy browser support
Example of installing and using plugins:
npm install @vitejs/plugin-vue @vitejs/plugin-legacy -D
import vue from '@vitejs/plugin-vue'
import legacy from '@vitejs/plugin-legacy'
export default defineConfig({
plugins: [
vue(),
legacy({
targets: ['defaults', 'not IE 11']
})
]
})
TypeScript Integration
Vite natively supports TypeScript without additional configuration. However, for a better development experience, you can:
- Configure path aliases in
tsconfig.json
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
- Synchronize the configuration in
vite.config.ts
:
import { resolve } from 'path'
export default defineConfig({
resolve: {
alias: {
'@': resolve(__dirname, 'src')
}
}
})
- Create
vite-env.d.ts
to enhance type hints:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
Multi-Page Application Configuration
Vite supports multi-page applications by configuring multiple entries in vite.config.ts
:
import { resolve } from 'path'
export default defineConfig({
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
about: resolve(__dirname, 'about.html'),
contact: resolve(__dirname, 'contact.html')
}
}
}
})
Corresponding project structure:
project/
├── about.html
├── contact.html
├── index.html
└── src/
├── about/
├── contact/
└── main/
Custom Middleware
Custom middleware can be implemented by configuring server.middlewareMode
and server.proxy
:
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
})
Or directly add custom middleware:
export default defineConfig({
server: {
middlewareMode: true,
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (req.url === '/custom') {
res.end('Hello from custom middleware')
} else {
next()
}
})
}
}
})
Performance Optimization Practices
- Dependency Pre-Building - Vite automatically pre-builds dependencies, but you can also manually configure them:
optimizeDeps: {
include: ['vue', 'vue-router', 'lodash-es'],
exclude: ['some-pkg']
}
- Use Modern Browser Features - Configure build targets:
build: {
target: 'esnext'
}
- Enable gzip/brotli Compression - Use plugins:
npm install vite-plugin-compression -D
import viteCompression from 'vite-plugin-compression'
export default defineConfig({
plugins: [
viteCompression()
]
})
Test Integration
Vite can easily integrate with various testing frameworks. Using Vitest as an example:
- Install dependencies:
npm install vitest happy-dom @testing-library/vue -D
- Configure
vite.config.ts
:
/// <reference types="vitest" />
export default defineConfig({
test: {
globals: true,
environment: 'happy-dom'
}
})
- Add test scripts to
package.json
:
{
"scripts": {
"test": "vitest"
}
}
- Write test files:
import { render } from '@testing-library/vue'
import MyComponent from './MyComponent.vue'
test('renders correctly', () => {
const { getByText } = render(MyComponent, {
props: { msg: 'Hello' }
})
getByText('Hello')
})
Deployment Strategies
Deploying a Vite application is very simple, mainly considering the following points:
- Static File Deployment - Directly deploy the
dist
directory after building - SPA Deployment - Configure the server to redirect to
index.html
- SSR Deployment - Requires a Node.js server environment
For static deployment, the build command is:
npm run build
The generated dist
directory structure:
dist/
├── assets/
│ ├── index.[hash].js
│ └── style.[hash].css
└── index.html
Example Nginx configuration:
server {
listen 80;
server_name example.com;
root /path/to/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn