Static resource handling strategy
Project Configuration and Basic Usage
The Vite.js configuration file is located at vite.config.js
in the project root directory. This file allows customization of build behavior, plugins, server options, and more. The basic configuration structure is as follows:
import { defineConfig } from 'vite'
export default defineConfig({
// Configuration options
})
Common configuration items include:
root
: Project root directory (default:process.cwd()
)base
: Public base path for development or production environment servicespublicDir
: Folder for static asset serving (default:'public'
)server
: Development server optionsbuild
: Build optionsplugins
: Array of plugins
Example development server configuration:
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
Static Asset Handling Strategy
Vite employs a unique approach to static asset handling, differing from traditional bundlers. The core strategies are as follows:
File Import Handling
Vite supports multiple ways to import static assets:
- Direct imports return the resolved URL
- Explicit URL imports using the
?url
suffix - String imports using the
?raw
suffix - Web worker imports using the
?worker
suffix
// 1. Direct import
import imgUrl from './img.png'
document.getElementById('hero-img').src = imgUrl
// 2. Explicit URL import
import workletURL from 'extra-scalloped-border/worklet.js?url'
CSS.paintWorklet.addModule(workletURL)
// 3. Raw string import
import shaderString from './shader.glsl?raw'
Public Directory Handling
Files in the public
directory:
- Are not processed by Vite
- Are directly copied to the root of the output directory
- Must be referenced using absolute paths
<!-- Reference favicon.ico from the public directory -->
<link rel="icon" href="/favicon.ico" />
Asset Inlining Threshold
Assets smaller than the assetsInlineLimit
option value (default: 4096, or 4kb) are inlined as base64 URLs. Larger assets are copied to the output directory with hashed filenames.
build: {
assetsInlineLimit: 8192 // 8kb
}
Custom Asset Handling
Extend the types of static assets recognized by Vite using the assetsInclude
option:
assetsInclude: ['**/*.gltf', '**/*.mov']
Special Asset Handling
JSON Files
JSON files can be directly imported and are automatically parsed:
import pkg from './package.json'
console.log(pkg.version)
Named imports are also supported:
import { version } from './package.json'
CSS Handling
Vite supports direct .css
file imports, with styles automatically injected into the page:
import './style.css'
CSS modules can be used via the .module.css
suffix:
import styles from './module.module.css'
document.getElementById('foo').className = styles.className
Static Asset Path Handling
When referencing static assets in templates, Vite automatically handles paths:
<img src="@/assets/logo.png" />
In JavaScript, use new URL
to dynamically obtain assets:
const imgUrl = new URL('./img.png', import.meta.url).href
Build Optimization Strategies
Code Splitting
Vite automatically performs code splitting. More granular splitting can be achieved via dynamic imports:
const module = await import('./module.js')
Manually specify split points:
build: {
rollupOptions: {
output: {
manualChunks: {
'vendor': ['vue', 'vue-router']
}
}
}
}
Asset Fingerprinting
During production builds, Vite automatically generates hashed filenames for assets:
build: {
assetsDir: 'static',
rollupOptions: {
output: {
assetFileNames: 'static/[name]-[hash][extname]',
chunkFileNames: 'static/[name]-[hash].js',
entryFileNames: 'static/[name]-[hash].js'
}
}
}
Dependency Pre-Bundling
Vite pre-bundles dependencies (modules in node_modules
) for performance. Manual configuration is possible:
optimizeDeps: {
include: ['vue', 'vue-router'],
exclude: ['vue-demi']
}
Advanced Asset Handling
WebAssembly Support
Vite supports direct .wasm
file imports:
import init from './module.wasm'
const instance = await init()
Web Workers
Workers can be imported via dedicated suffixes:
// worker.js
self.onmessage = (e) => {
console.log(e.data)
self.postMessage('pong')
}
// Main thread
import MyWorker from './worker?worker'
const worker = new MyWorker()
worker.postMessage('ping')
Binary Assets
Binary assets can be imported via ?url
or ?buffer
suffixes:
import wasmUrl from './module.wasm?url'
import wasmBuffer from './module.wasm?buffer'
Multi-Page Application Handling
For multi-page applications, configure multiple entry points:
build: {
rollupOptions: {
input: {
main: 'index.html',
about: 'about.html',
contact: 'contact.html'
}
}
}
Each HTML file corresponds to a separate entry point, and Vite automatically handles dependencies.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:环境变量与模式管理
下一篇:CSS/预处理器集成配置