- ServePlugin - the background image path parsed by the Unocss custom rules is mapped to the real image resource.
- BuildPlugin - pack the background image into
./dist
, add a hash value to the background image and css.
In Unocss, custom rules cannot handle static background image references, which may cause errors in packaging or incorrect access positions of the packaged images.
The author gives some suggestions.
However, it is inevitable that there will still be a need to use static files as background images in projects. This plugin initially solves this problem.
pnpm add vite-plugin-unocss-bgimg
// vite.config.ts
import UnocssBgImg from 'vite-plugin-unocss-bgimg'
...
export default defineConfig({
...
plugins: [
...
UnocssBgImg({
src: './src/assets/bgimgs', // The path where the background image is stored
dest: 'assets', // The location where the background image is stored after packaging.(ex: ./dist/assets/xxx.png => dest: 'assets')
}),
],
})
// unocss.config.ts
...
const imgTypeReg = /(http|https):\/\/([\w.]+\/?)\S*/
export default defineConfig({
...
rules: [
...
[/^bgi-\[([\w\W]+)\]$/, ([, d]) => {
// '/assets' is the location of dest in your plugin configuration(dest: 'assets').
const path = `${imgTypeReg.test(d) ? '' : '/assets/'}`
return ({ 'background-image': `url('${path}${d}')` })
}],
],
})
Now, you can use your custom rules for normal development, and the packaging will not report errors.
<template>
<div class="bgi-[line.png]">
</template>
// line.png is stored in the location corresponding to src in the config(src: './src/assets/bgimgs').