Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

Vite SVG loader


Vite plugin to load SVG files as Vue components, using SVGO for optimization.

  1. ``` vue
  2. <template>
  3.   <MyIcon />
  4. </template>

  5. <script setup>
  6. import MyIcon from './my-icon.svg'
  7. </script>
  8. ```

Install


  1. ``` shell
  2. npm install vite-svg-loader --save-dev
  3. ```

Setup


vite.config.js


  1. ``` js
  2. import svgLoader from 'vite-svg-loader'

  3. export default defineConfig({
  4.   plugins: [vue(), svgLoader()]
  5. })
  6. ```

Import params


URL


SVGs can be imported as URLs using the ?url suffix:

  1. ``` js
  2. import iconUrl from './my-icon.svg?url'
  3. // '/assets/my-icon.2d8efhg.svg'
  4. ```

Raw


SVGs can be imported as strings using the ?raw suffix:

  1. ``` js
  2. import iconRaw from './my-icon.svg?raw'
  3. // '...'
  4. ```

Component


SVGs can be explicitly imported as Vue components using the ?component suffix:

  1. ``` js
  2. import IconComponent from './my-icon.svg?component'
  3. //
  4. ```

Default import config


When no explicit params are provided SVGs will be imported as Vue components by default. This can be changed using the defaultImport config setting, such that SVGs without params will be imported as URLs (or raw strings) instead.

vite.config.js


  1. ``` js
  2. svgLoader({
  3.   defaultImport: 'url' // or 'raw'
  4. })
  5. ```

SVGO Configuration


vite.config.js


  1. ``` js
  2. svgLoader({
  3.   svgoConfig: {
  4.     multipass: true
  5.   }
  6. })
  7. ```

Disable SVGO


vite.config.js


  1. ``` js
  2. svgLoader({
  3.   svgo: false
  4. })
  5. ```

Skip SVGO for a single file


SVGO can be explicitly disabled for one file by adding the ?skipsvgo suffix:

  1. ``` js
  2. import IconWithoutOptimizer from './my-icon.svg?skipsvgo'
  3. //
  4. ```

Use with TypeScript


If you use the loader in a Typescript project, you'll need to import your svg files with the ?component param: import MyIcon from './my-icon.svg?component'.

You'll also need to reference the type definitions:

  1. ``` ts
  2. ///
  3. ```

Sponsors


Thanks to Nexxtmove for sponsoring the development of this project.Your logo or name here? Sponsor this project.
Last Updated: 2023-05-23 11:11:51