craft-vite
craft-vite copied to clipboard
Add support for referencing src paths to craft.vite.inline()
Is your feature request related to a problem? Please describe.
At present, I include SVGs built from Vite using both .asset()
and .inline()
{% set logoPath = craft.vite.asset('src/images/logo.svg') %}
{{ logoPath|default ? craft.vite.inline(logoPath)|attr({"class": "w-12"}) }}
This works, but is inlining the file from the full URL, whereas I would greatly prefer to use the local file path.
Describe the solution you would like
I would like to be able to pass the src path straight into the inline function.
{{ craft.vite.inline('src/images/logo.svg')|attr({"class": "w-12"}) }}
This would need to reference the manifest to get the built file path, and likely use @webroot
to access the file. It may require an additional config setting for the path to dist.
Describe alternatives you have considered
Alternatively, .asset()
could accept an additional parameter to return only the file path.
{% set logoPath = craft.vite.asset('src/images/logo.svg', public=false, pathOnly=true) %}
{{ logoPath }} # outputs 'dist/assets/images/logo-bbdb01c5.svg', which can then be concatenated with '@webroot'
{{ craft.vite.inline("@webroot/#{logoPath}")|attr({"class": "w-12"}) }}
I am running into similar issues and I think they might actually be the same: When inlining SVGs with craft.vite.inline
from src/assets
, after bundling with vite the src
folder also has to be deployed.
How can I help to resolve this issue? :)
PRs are welcome!
Similar to: https://github.com/nystudio107/craft-plugin-vite/issues/22
So two things here...
-
Vite has a file cache, so while using the pattern you're describing here, it will do a web request the first time, after that the inline will come from the cache, so there won't be additional web requests until the cache is cleared
-
The
craft.vite.inline()
method takes either a local path or a URL... so you could take the URL returned, and manipulate it into a file path
Currently, the Vite plugin has no awareness at all of web root file system paths except for the $manifestPath
, so something like the PR would need to be implemented to change that... but there are work-arounds mentioned above.
Also in general, if you're having Vite process assets (like SVGs), the expectation is that they will be loaded via JavaScript. If you have a bunch of SVG icons that you're not loading via JavaScript, probably the best thing to do is just put them into your Vite public/
directory so they are copied into dist/
but will not be version hashed.
That way you know the fixed path that they will always be referenced from. You don't really gain anything by version hashing them or running them through Vite, unless I suppose you change them with some frequency, and thus want the version hash for cache busting purposes.