2

I'm building a Ionic-Vue 5 mobile app and I'm finding myself import a lot of vue components just to use them into my views:

import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonInput,
  IonButton,
  IonAlert,
  IonList,
  IonItem,
  IonCard,
  IonCardContent,
  IonCardHeader,
  IonCardSubtitle,
  IonLabel,
  IonSpinner
} from "@ionic/vue";

export default defineComponent({
  components: {
    IonHeader,
    IonToolbar,
    IonTitle,
    IonContent,
    IonPage,
    IonInput,
    IonButton,
    IonAlert,
    IonList,
    IonItem,
    IonCard,
    IonCardContent,
    IonCardHeader,
    IonCardSubtitle,
    IonLabel,
    IonSpinner
  },

I know this could be useful from a performance point of view, but there is a way to just import all ionic components at once when the list is big enough to justify a little performance loss in order to greatly simplify the code?

Suxsem
  • 90
  • 1
  • 7
  • I'm also looking to do this, as importing 100+ components is just ridiculous! I was considering creating a mixin which just includes every component. Did you manage to find a better solution? – James Dec 11 '20 at 13:13

2 Answers2

6

In main.js (or wherever you create your Vue app):

import * as IonComponents from '@ionic/vue';

Object.keys(IonComponents).forEach(key => {
    if (/^Ion[A-Z]\w+$/.test(key)) {
        app.component(key, IonComponents[key]);
    }
});

If it's before you've created your Vue app, just swap in Vue.component(…) in place of app.component(…).

The regex ensures that only the components get registered as components, they all start with Ion. The other items in that import are mostly functions, which you'll need to import when needed.

Troy Gilbert
  • 687
  • 3
  • 8
  • Worth mentioning that this way the whole library of components is loaded, even the ones not used, so the bundle size will be bigger. Something to consider mainly if developing a PWA – Paranoid Android Nov 02 '22 at 14:50
0

You can always do something like app.component('ion-app', IonApp) in your main.js after you have initialized the app variable.

By doing so, you are basically importing all the components once and making those available to all the components.

Now you can directly use <ion-app>...</ion-app> in your templates without importing the ionic components everytime.

Noopur Phalak
  • 878
  • 1
  • 13
  • 22