vite-plugin-vue-images

Auto import images for Vite+Vue projects
23,237 11
Install
npm install vite-plugin-vue-images
Latest Version:0.6.1
License:MIT
Last Updated:Jan 19, 2025
Links: GitHub  ·  npm
Maintainer: sampullman

Usage

Only works with Vite 2 & Vue 3.

Install

npm i vite-plugin-vue-images -D

Add to vite.config.js

// vite.config.js
import Vue from '@vitejs/plugin-vue'
import ViteImages from 'vite-plugin-vue-images'

export default {
  plugins: [
    Vue(),
    ViteImages()
  ],
};

Use images in templates without import-ing and exposing via data. Image names are converted to PascalCase. Duplicate image names are not supported at this time. Currently, v-bind:src or the shorthand :src must be used.

Images in subdirectories are referenced by prepending the directory structure, e.g. src/assets/img/icon/star.png becomes IconStar. This behavior may change in the future, or become configurable.

WARNING: Variables (props, data) will be clobbered in templates if they conflict with image names

The plugin will convert this:

<template>
<img :src="https://raw.githubusercontent.com/sampullman/vite-plugin-vue-images/HEAD/Image1" />
</template>

<script>
export default {
  name: 'app',
};
</script>

into this:

<template>
<img :src="https://raw.githubusercontent.com/sampullman/vite-plugin-vue-images/HEAD/TestImage1" />
</template>

<script>
import TestImage1 from '/src/assets/img/test_image1.jpg'

export default {
  name: 'App',
  data() {
    return {
      TestImage1,
    };
  },
};
</script>

Configuration

Default configuration values:

ViteImages({
  // Relative paths of image search directories
  dirs: ['src/assets/img'],

  // valid image extensions
  extensions: ['jpg', 'jpeg', 'png', 'svg', 'webp'],

  // Override default behavior of name -> image path resolution
  customResolvers: [],

  // Override Regex that searches for variables to replace. MUST include group
  customSearchRegex: '([a-zA-Z0-9]+)',
});

Example

See the example directory.

Thanks

Thanks to @antfu and @brattonross. This project is inspired by vite-plugin-components, which is in turn inspired by vite-plugin-voie.

License

MIT License © 2021 Samuel Pullman

Related Packages

vite-plugin-source-identifier

A Vite plugin that adds source location and component information to DOM element...

797,687
vite-plugin-vue-meta-layouts

vite 的 vue-router 的元信息布局系统

314,627 65
vite-plugin-vue-docgen

A simple vue-docgen plugin for Vite

91,834 8
vite-plugin-source-info

A Vite plugin that adds source location and component information to DOM element...

14,961
vite-plugin-favicons-inject

A Vite plugin for creating and injecting favicons during the application build!

533,525 10

Version History

Version Released License
0.6.1 MIT
0.6.0 MIT
0.5.0 MIT
0.4.1 MIT
0.4.0 MIT