Support lazy dynamic imports, e.g. `() => import()`
patricknelson opened this issue · 0 comments
Describe the problem
Inspired by @baseplate-admin from #31 (comment):
So the problem i faced was, the project I am working on is large in nature ( 10+ MB ). I want to split split each svelte component into it's own
.js
file, instead of using one large bundle file. This drastically improves the FOUC performance of the website.
For large projects that implement many custom elements using svelte-retag
, one great way to help organize code and potentially boost performance would be to use of dynamic import()
statements which are only called when they are needed (i.e. lazily).
Describe the proposed solution
Add the ability to define svelte-retag
custom elements using "lazy dynamic imports". That is, more specifically: Not import()
or await import()
but instead () => import()
, i.e.: an arrow function which returns a Promise
.
e.g.
svelteRetag({
component: () => import('./HelloWorld.svelte'),
tagname: 'hello-world',
});
This could be used to enable the ability of defining custom elements like <hello-world>
ahead of time without necessarily importing them until after they're actually used in the HTML/DOM.
Bonus: This may also open up the opportunity of efficiently defining many components in bulk using Vite's Glob Import feature import.meta.glob('./**/*.svelte')
.
While both regular (i.e. lazy dynamic imports) and eager dynamic imports (i.e. with { eager: true }
) are possible, both approaches will result in either:
- With
{ eager: true }
: All modules bundled together into a single file (no code splitting) - Without
{ eager: true }
: All modules are code split, but get loaded on every page load (due to every module always beingawait
'ed).
With this, we can not only get code splitting but only await
the necessary modules for the current page based on the tags currently mounted on the page.
Alternatives considered
Dynamic import()
's are already possible, however they require more effort to setup and must be done outside of svelte-retag
, for example:
import svelteRetag from 'svelte-retag';
svelteRetag({
component: (await import('./HelloWorld.svelte')).default,
tagname: 'hello-world',
});
This can be problematic since it requires separating things into more .js
/.ts
files and manually including them in the pages where they are needed and potentially causing some code duplication in multiple bundle files. It would also be a nice DX boost to automatically support Vite's default import.meta.glob
out-of-the-box without having to worry that every module is always being loaded on every single page (see above).
Importance
would make my life easier