Master Vite’s Static Asset Handling: 5 Methods Explained in 10 Minutes
This article walks through Vite's five static asset handling strategies—including public directory paths, import queries like ?url, ?raw, and ?worker—showing code examples, middleware behavior, and build‑time transformations so developers can quickly understand and apply each method.
1. Five ways to handle static assets in Vite
(1) Use root absolute path for resources in public
Files placed in publicDir (default public) are served directly and must be referenced with a leading slash, e.g. /wy-logo.png. JavaScript files should not import these assets. <img alt="Vue logo" src="/wy-logo.png" /> publicDir is the directory for static assets, default public.
Reference public assets with root absolute path, e.g. /wy-logo.png, which resolves to ${yourHost}/wy-logo.png.
Do not import public assets from JavaScript.
The server adds a middleware when config.publicDir is set:
if (config.publicDir) {
middlewares.use(servePublicMiddleware(config.publicDir))
}(2) General import of static assets (returns resolved public path)
Vite treats files with extensions listed in KNOWN_ASSET_TYPES or matched by assetsInclude as importable assets. Importing such a file returns a URL that can be used as src.
<template>
<img alt="Vue logo" :src="starImg" />
</template>
<script>
import starImg from '../assets/star.png'
export default defineComponent({
data () {
return { starImg }
}
})
</script>Each import is transformed into a request with ?import and the resolved URL is returned.
import logo from '../../public/wy-logo.png'
console.log(logo)(3) Non‑general assets – explicit URL import ?url
Appending ?url forces Vite to treat the file as a plain URL.
export const nameList = ['Tim','John','Bob','Catherine']
console.log(`名称列表 = `, nameList.join(' '))In a component:
import nameListUrl from '../data/name.js?url'
console.log(nameListUrl) // → '/src/data/name.js'(4) Import as raw string ?raw
Using ?raw returns the file content as a string.
import nameString from '../data/name.js?raw'
console.log(nameString) // → export default "..."(5) Import script as Web Worker ?worker / ?sharedworker
Appending ?worker or ?sharedworker turns the module into a Web Worker.
export const nameList = ['Tim','John','Bob','Catherine']
addEventListener('message', (e) => {
console.log('主线程: ', e.data)
postMessage({ word: `Hi,我是 worker~~ 老大,这是你要的名单:${nameList.join(' ')}`, nameList })
close()
}, false)Component usage:
import NameWorker from '../data/name-worker.js?worker'
export default defineComponent({
mounted () {
const worker = new NameWorker()
worker.postMessage('Hi, 我是主线程~')
worker.onmessage = (e) => {
if (e.data) {
console.log('Worker:', e.data.word)
this.workerNameList = e.data.nameList
worker.terminate()
}
}
worker.onerror = (e) => console.log('ERROR:', e.message)
}
})During development the webWorkerPlugin resolves the worker URL; in production the plugin can inline the worker code or emit it as a separate chunk.
2. Summary
Vite distinguishes static assets by special query strings ( ?worker, ?sharedworker, ?raw, ?url) and processes them with dedicated transform hooks. Files in publicDir are served directly, while other assets are imported as URLs, raw strings, or workers, each with its own handling logic.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
WeDoctor Frontend Technology
Official WeDoctor Group frontend public account, sharing original tech articles, events, job postings, and occasional daily updates from our tech team.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
