jpkleemans / vite-svg-loader

Vite plugin to load SVG files as Vue components
MIT License
557 stars 59 forks source link

Feature: Add default import config option #42

Closed floorish closed 2 years ago

floorish commented 2 years ago

Added defaultImport config option, to change the import type when no explicit query param is defined. Can be 'url' | 'raw' | 'component' (default is component).


Testing with cypress (the following is not necessary when using vite-svg-loader in projects, this is only used for testing vite-svg-loader itself)

vite.config.js dynamically inserts the defaultImport option from environment vars. Can be defined in .env:

VITE_SVG_DEFAULT_IMPORT=url

Or when calling the npm build script:

npm --svg_default_import=url run example:build

App.vue needed to be updated, because when defaultImport === 'url' the following will cause an error while rendering:

import Test from './assets/test.svg' // <--- this is now a url, not a component
<Test class="test-svg" data-animal="bird" aria-hidden="true" /> // <--- this fails to render

So that needs to be:

import Test from './assets/test.svg?component'
<Test class="test-svg" data-animal="bird" aria-hidden="true" />

Therefore vite.config.js also dynamically resolves App.vue to either './App.vue' or './App-url.vue' depending on the SVG_DEFAULT_IMPORT environment setting.

jpkleemans commented 2 years ago

Thanks for your work! I'm a little busy at the moment, but I'll look into it soon.

ppfeiler commented 2 years ago

When this gets merged, do we still need to specify ?component when importing an SVG with Typescript?

floorish commented 2 years ago

Yes, you still need to do that. You need to specify ?component anyway if you set the defaultImport to url. If you don't change the defaultImport setting nothing changes.

jpkleemans commented 2 years ago

Thanks for your work

floorish commented 2 years ago

Cheers, thanks for the plugin!