Since Svelte does not use a virtual-dom, it turns out the interoperability with web components is very good. Svelte is capable of creating web components as well. These two features make it play well with with Ionic and the Ionic router.
You can see an example on the svelte REPL here.
The Ionic router has a good emulation of the routing transitions used on iOS and Android and I think the combination of svelte and Ionic are quite powerful.
In the example, we load the Ionic web components and CSS thought a CDN:
<svelte:head>
<script
type="module"
src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js">
</script>
<script
nomodule
src="https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js">
</script>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css" />
</svelte:head>
NOTE: It may look like you are loading a lot of code, but Ionic's web components are instantiated lazily, so only loaded when used. This improves your startup performance and Lighthouse scores.
The Ionic router works by routing to to web components. I.e. the way we make this work with svelte, is that we create a web component out of any route/page and refer to it in the tag.
This code:
import { register } from "svelte-custom-elements";
import NavHome from "./NavHome.svelte";
const isRegistered = function(name) {
return document.createElement(name).constructor !== HTMLElement;
};
if (!isRegistered("nav-home")) {
register("nav-home", NavHome, []);
}
essentially imports our svelte component and then registers it as a web component called "nav-home". NOTE: web component names must be unique. The last lines above are to ensure that when using hot module reload, the web component is not redefined, else you will get an error.
The Ionic router has path based and programmatic routing, which I will explore more in future posts.
Top comments (0)