How to use Ionic with Astro?

Hi Community,

is there any good tutorial or best practices how to use Ionic Components with Astro?

Best Regards,
Marius

1 Like

Why would you want to use 2 front-end frameworks in 1 project? What’s the purpose?

Hi @Hills90210,

I assume you also use Ionic together with another frontend framework like Angular, React or Vue? Then why not together with Astro? I would like to use Astro as the base framework and Ionic as a UI library. I don’t want people to be able to see the HTTP requests to the rest API, which is why I want to use a SSR framework like Astro to execute the requests on the server side. Does that answer your question?

My current implementation:

Install Dependencies
yarn add @ionic/core
yarn add -D sass

Now go to your Layout.astro File.

Add Styles
Option 1: Add Styles as reference in the <head> Section

---
import "@ionic/core/css/ionic.bundle.css";
---

Option 2: Add Styles inline

<style lang="scss" is:global>
 @import "@ionic/core/css/ionic.bundle.css";
</style>

Add the scripts

<head>
	...
	<script type="module" src="node_modules/@ionic/core/dist/ionic/ionic.esm.js"></script>
	<script nomodule src="node_modules/@ionic/core/dist/ionic/ionic.js"></script>
	...
</head>

Force Platform Style (optional)

<html lang="en" class="ios">
...
<body>
  <slot />
    <script>
      document.querySelector('html')?.classList.remove('md');
      document.querySelector('html')?.setAttribute('mode', 'ios');
    </script>
</body>
...
<html>

Use the Components like normal HTML in your Pages. Use the Controllers like that:

<script>
  import { loadingController } from "@ionic/core";

  document.querySelector("ion-button")?.addEventListener("click", async () => {
    const loading = await loadingController.create({
      message: "hi",
      duration: 5000,
    });

    await loading?.present();
  });
</script>

Now you should have a super fast mobile website!
If you have some improvements, please let me know!

Kind regards,
Marius

2 Likes