vue.jsionic-frameworkionic-vue

Import all ionic components into a Ionic-Vue view


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?


Solution

  • 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.