nystudio107 / craft-plugin-vite

Plugin Vite is the conduit between Craft CMS plugins and Vite, with manifest.json & HMR support
MIT License
12 stars 11 forks source link

on demand loading of external files #13

Closed samuelbirch closed 1 year ago

samuelbirch commented 1 year ago

Hi,

I'm trying to get a setup where i can use the craft.vite.register to only load in an external file (library) when needed, on the whole this is working ok(ish) but i'm running into a few issues i'm hoping you can help with.

In the vite.config.js file i have this in the build options: rollupOptions: { input: { app: root+'/src/js/app.js', htmx: 'htmx.org', splide: '@splidejs/splide', }, }

now in a twig partial i add this {{ craft.vite.register("node_modules/htmx.org/dist/htmx.min.js") }} and it works fine both with the devServer and in production.

First question: I haven't been able to figure out how or if possible to modify the key in the the manifest file to use the value from the rollupOptions above instead of using the full location. So ideally i'll like to use {{ craft.vite.register("htmx.org") }} - if this is not possible to do via vitejs options is it possible to tweak this plugin to allow for partial matches on the manifest keys?

This also leads onto another issue. When referencing the Splide lib: {{ craft.vite.register("node_modules/@splidejs/splide/dist/js/splide.js") }} this works on the devServer, but not in production. When built the manifest uses the esm version and therefore this full location it not in the manifest file. - This would be solved with the ability to use partial matches.

Second question: When I update the location to match the one in the manifest file to test it out. The file loads (apparently) but the global object which the lib is providing (Splide) which works in the devServer is not to be found in production. - I know this nothing to do with this plugin, but i hoping you may have come across this issue before and know how to resolved it?

Thanks

khalwat commented 1 year ago

So I had some answers typed out, but it occurred to me that a better answer is that the approach you're taking is probably fighting things more than it should be.

It feels like you're trying to use Vite like you might use Gulp, or some other task runner. That may be fighting its true nature a bit.

The things you put in input should be the entrypoint Javascript files... these libraries are not really entry points, but rather get used by other Javascript code I presume.

That being the case, why not just include these various libraries that you need via your Javascript code?

Examples:

Also you could use dynamic imports to import JS code dynamically, and handle the conditional loading that way.

I think your current approach is probably making things harder for you than it should be, unless I'm missing something.

samuelbirch commented 1 year ago

Thanks, i came to the same conclusion last night as well. Got it all working now :)