SpiriitLabs / vite-plugin-svg-spritemap

Vite plugin to generate svg spritemap
MIT License
53 stars 4 forks source link

Usage in laravel 10 #31

Closed Peeet93 closed 9 months ago

Peeet93 commented 11 months ago

Hi there,

did you already use this plugin in laravel? If so, how do i integrate the svg file for "vite --host"? If i use {{ Vite::asset("spritemap.svg") }} it is working for "vite build", but not for the dev version.

I also added the HMR script inside the body, but the path is still "http://localhost:5174/spritemap.svg#sprite-mail"

Thanks in advance

Applelo commented 11 months ago

Hi, I haven't use laravel since 2018 so I can't tell you exactly how to do it 😄 . Nice, if it is already working for you in build. To make it work on dev, you need to detect when ViteJS is in dev mode and handle the sprite url manually. ViteJS can't access your HTML and accessing the svg generated by the plugin generate CORS errors. So, I recommend to use the injectSVGOnDev option in the plugin options.

// vite.config.js / vite.config.ts
import VitePluginSvgSpritemap from '@spiriit/vite-plugin-svg-spritemap'

export default {
  plugins: [
    VitePluginSvgSpritemap('./src/icons/*.svg', {
      injectSVGOnDev: true
    })
  ]
}

You will need to add to your template this line of code only when ViteJS is running.

<script type="module" src="http://localhost:5173/@vite-plugin-svg-spritemap/client"></script>

This will inject directly the svg spritemap inside your code thanks to the script above. So in dev, you need to invoke your sprite like this.

<svg>
  <use xlink:href="#sprite-spiriit"></use>
</svg>

and in prod, you should change the url manually to something like this:

<svg>
  <use xlink:href="https://my-cool-website.com/dist/assets/spritemap.95b4c41a.svg#sprite-spiriit"></use>
</svg>
Applelo commented 10 months ago

I have updated the demo folder with an example of integration with vite as backend.

Applelo commented 9 months ago

I close the issue, feel free to reopen it if you have more question.