Skip to content

yekezz/vite-plugin-unocss-bgimg

Repository files navigation

vite-plugin-unocss-bgimg

NPM version

Features

  • 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.

Resolve

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.

Usage

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').

License

MIT License © 2022 Enoch

About

Extend custom background image rules in unocss

Resources

License

Stars

Watchers

Forks

Packages

No packages published