Build target and multi-page application configuration
Vite.js, as a modern front-end build tool, is favored by developers for its lightning-fast startup speed and hot module replacement capabilities. Project configuration and basic usage are key to mastering Vite, while build targets and multi-page application configurations can address more complex scenario requirements.
Project Initialization and Basic Configuration
Creating a project with Vite is very simple. You can quickly initialize it with the following command:
npm create vite@latest my-project --template vue
After initialization, the project directory will generate a vite.config.js
file, which is the core configuration file for Vite. Basic configurations typically include:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true
},
build: {
outDir: 'dist'
}
})
This basic configuration includes:
- Plugin system (using the Vue plugin)
- Development server configuration (port and auto-opening the browser)
- Build output directory settings
Build Target Configuration
Vite supports multiple build targets, allowing you to output code in different formats based on requirements:
export default defineConfig({
build: {
target: 'es2015',
outDir: 'dist',
assetsDir: 'assets',
emptyOutDir: true,
rollupOptions: {
output: {
entryFileNames: `assets/[name].js`,
chunkFileNames: `assets/[name].js`,
assetFileNames: `assets/[name].[ext]`
}
}
}
})
Detailed explanation of build target configuration:
target
: Sets the browser compatibility target for the final build.outDir
: Specifies the output directory.assetsDir
: Path for static assets.emptyOutDir
: Clears the output directory before building.rollupOptions
: Rollup packaging configuration.
For different scenarios, you can set different build targets:
// Modern browsers
target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14']
// Compatibility with older browsers
target: ['es2015', 'ie11']
Multi-Page Application Configuration
Vite natively supports multi-page application (MPA) configuration. Compared to single-page applications (SPAs), MPAs require more complex configurations:
import { resolve } from 'path'
export default defineConfig({
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
about: resolve(__dirname, 'about/about.html'),
contact: resolve(__dirname, 'contact/contact.html')
}
}
}
})
The directory structure for a multi-page application typically looks like this:
project/
├── index.html
├── about/
│ ├── about.html
│ └── about.js
├── contact/
│ ├── contact.html
│ └── contact.js
└── vite.config.js
For more complex multi-page applications, you can dynamically generate configurations:
import fs from 'fs'
import path from 'path'
function getPageEntries(dir) {
const pagesDir = path.resolve(__dirname, dir)
return fs.readdirSync(pagesDir).reduce((entries, page) => {
const pagePath = path.join(pagesDir, page)
if (fs.statSync(pagePath).isDirectory()) {
entries[page] = path.join(pagePath, 'index.html')
}
return entries
}, {})
}
export default defineConfig({
build: {
rollupOptions: {
input: {
main: path.resolve(__dirname, 'index.html'),
...getPageEntries('pages')
}
}
}
})
Advanced Multi-Page Configuration Techniques
For large projects, more granular control may be needed:
- Shared Dependency Configuration:
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules')) {
return 'vendor'
}
}
}
}
}
- Custom Page Templates:
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
pages: [
{
entry: 'src/main.js',
filename: 'index.html',
template: 'index.html',
injectOptions: {
data: {
title: 'Home'
}
}
},
{
entry: 'src/about.js',
filename: 'about.html',
template: 'about.html',
injectOptions: {
data: {
title: 'About Us'
}
}
}
]
})
]
})
- Environment Variables and Multi-Page Integration:
// .env
VITE_APP_TITLE=My App
// vite.config.js
import { loadEnv } from 'vite'
export default ({ mode }) => {
const env = loadEnv(mode, process.cwd())
return defineConfig({
plugins: [
createHtmlPlugin({
inject: {
data: {
title: env.VITE_APP_TITLE
}
}
})
]
})
}
Performance Optimization Configuration
Multi-page applications especially require attention to performance optimization:
export default defineConfig({
build: {
chunkSizeWarningLimit: 1000,
cssCodeSplit: true,
sourcemap: false,
minify: 'terser',
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
}
})
For static assets like images:
export default defineConfig({
assetsInclude: ['**/*.glb', '**/*.gltf'],
build: {
assetsInlineLimit: 4096 // Files under 4kb will be converted to base64
}
})
Development Server Special Configuration
Multi-page applications may require special configurations during development:
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
}
})
Hot module replacement configuration:
export default defineConfig({
server: {
hmr: {
overlay: false
}
}
})
Integration with Other Tools
Vite can seamlessly integrate with other tools:
- Integration with Tailwind CSS:
export default defineConfig({
css: {
postcss: {
plugins: [
require('tailwindcss'),
require('autoprefixer')
]
}
}
})
- Integration with SVG Components:
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]'
})
]
})
- Integration with PWA:
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'apple-touch-icon.png'],
manifest: {
name: 'My App',
short_name: 'App',
start_url: '/',
display: 'standalone',
background_color: '#ffffff',
theme_color: '#000000',
icons: [
{
src: 'pwa-192x192.png',
sizes: '192x192',
type: 'image/png'
}
]
}
})
]
})
Common Issue Solutions
- Routing Conflict Issues:
// vite.config.js
export default defineConfig({
server: {
historyApiFallback: {
rewrites: [
{ from: /^\/about/, to: '/about/index.html' },
{ from: /^\/contact/, to: '/contact/index.html' }
]
}
}
})
- Static Asset Path Issues:
export default defineConfig({
base: '/my-app/',
build: {
assetsDir: 'static'
}
})
- Environment Variable Usage Issues:
// .env
VITE_API_URL=https://api.example.com
// Usage in components
const apiUrl = import.meta.env.VITE_API_URL
- Multi-Page CSS Extraction Issues:
export default defineConfig({
build: {
cssCodeSplit: true,
rollupOptions: {
output: {
assetFileNames: 'assets/[name].[ext]'
}
}
}
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:Webpack5新特性解析
下一篇:自定义HTML模板