jpkleemans / vite-svg-loader

Vite plugin to load SVG files as Vue components
MIT License
590 stars 61 forks source link

import as `?component` in `<script>`, but as `?url` in `<template>` #153

Open mrleblanc101 opened 2 hours ago

mrleblanc101 commented 2 hours ago

Hi, Would it be possible to auto-detect where the import is from, and change the defaultImport accordingly ? For exemple, in a Vue SFC, if I import inside the <script> tag, I always want to import as a component like so:

<script setup>
import IconDelete from '@/assets/icon/delete.svg'
</script>

<template>
    ...
    <IconDelete width="24" height="24" />
    ...
</template>

But if I import from the template, I want it to be imported as an url, like so:

<template>
    <img src="@/assets/img/someComplexGraphic.svg" />
</template>

Currently, we have set our defaultImport to url, and manually add ?component to every import inside our script tags like so if we want both behavior to work:

<script setup>
import IconDelete from '@/assets/icon/delete.svg?component'
</script>

<template>
    ...
    <IconDelete width="24" height="24" />
    <img src="@/assets/img/someComplexGraphic.svg" />
    ...
</template>
mrleblanc101 commented 2 hours ago

This is because our svgoConfig removes all stroke|fill (see bellow) attribute so we can style the icons with CSS using svg { fill: currentColor } or svg { fill: #someColor }, but when we have an SVG in the template inside an <img> tag, we never want to process it with svgo.

I guess we could default to defaultImport: 'component' and instead add the ?url or ?skipSvgo to the SVG in the template, but it would be nice to automatically detect it.

svgoConfig: {
    plugins: [
        'prefixIds',
        'removeTitle',
        'removeDesc',
        'removeDimensions',
        {
            name: 'removeAttrs',
            params: {
                attrs: '(fill|stroke)',
            },
        },
    ],
},