Ionic Capacitor Vite, Vue (4 parts)


1. How to create a mobile app with Vite, Vue and Ionic Capacitor in 8 minutes including explanations

Capacitor is an open source native runtime for building Web Native applications. Build cross-platform iOS, Android, and Progressive Web Apps (PWAs) with JavaScript, HTML, and CSS.

Vite (French for “quick”) is a build tool that aims to enable faster and more economical development of modern web projects. It consists of two main parts: the dev (development) server and the build (build) command.

In 8 minutes, I explain how to create a vue js project with vite, convert it into a mobile app, and deploy it to the simulator with live-reload (live reload) for an efficient development process.

You can build your mobile app without using Ionic Framework Components so this process is not included, but leave a comment below if you’d like to see it.

Also, the same process should work with ReactJS and ViteJS.

Note

99.99% of this process was done with Ionic VS Code Plugin, but to file package.json changes have been made to make it work. live reload.

Live Reload is useful for debugging both the application web part and native functionality on the hardware device or simulators. Instead of deploying a new native app binary every time you make a change to the code, it reloads the browser (or Web View) when changes are detected in the app. — from the capacitor website

Line 11 previously said npm run dev

Links:


2. Using Ionic Capacitor Plugins in VueJS Vite Mobile App

Earlier we talked about building mobile apps with vue, Vite And Ionic Capacitor.

In this video we will use plugins Capacitor Camera And Capacitor Action Sheet to improve the user experience without relying on the Ionic Framework. If you use the PWA Elements version of these plugins, they can be applied to PWAs (Progressive Web Applications) running in the browser or on the device.

Installing the required libraries

Install plugins first

npm install @capacitor/camera
npm install @capacitor/action-sheet

Then sync the changes with capacitor

npx cap sync

Next, we need to install PWA Elements, which provide a web user interface when the app is not running on a mobile device. More information about PWA Elements can be found here at capacitor documentation.

npm install @ionic/pwa-elements

Project Code Modification

I need the element loader after installing the main component of the application.

Add the following code to the file main.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

import { defineCustomElements } from '@ionic/pwa-elements/loader';

createApp(App).mount('#app')

// Call the element loader after the app has been rendered the first time
defineCustomElements(window);

Action Sheet

Let’s start with Action Sheet (list of actions), change the code in the section script setup V App.vue. This code is copied directly from the Capacitor documentation linked above.

<script setup lang="ts">
import HelloWorld from "./components/HelloWorld.vue";

// New Import for ActionSheet Plugin
import { ActionSheet, ActionSheetButtonStyle } from "@capacitor/action-sheet";

// New function to render the ActionSheet
const showActionSheet = async () => {
  const result = await ActionSheet.showActions({
    title: "Photo Options",
    message: "Select an option to perform",
    options: [
      {
        title: "Upload",
      },
      {
        title: "Share",
      },
      {
        title: "Remove",
        style: ActionSheetButtonStyle.Destructive,
      },
    ],
  });

  console.log("Action Sheet result:", result);
};
</script>

Finally, we have a template that needs a button to fire an event to call a function showActionSheet.

<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="https://habr.com/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="https://habr.com/ru/company/otus/blog/725382/./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue + Ionic Capacitor" />
  <button @click="showActionSheet">SHOW ACTION SHEET</button>
</template>

Camera

Since we’ve already installed the plugins, let’s jump right into the code.

Inside the script section App.vue add the necessary imports

import { Camera, CameraResultType } from '@capacitor/camera';
import { ref } from "vue";

and a new snapshot feature.

// ref for image from camera
const imageUrl = ref<string|undefined>()

// camera
const takePicture = async () => {
  const image = await Camera.getPhoto({
    quality: 90,
    allowEditing: true,
    resultType: CameraResultType.Uri
  });

  imageUrl.value = image.webPath;
};

In the template, we will add an event activation button to call the new function to create a photo, as well as an image HTML element to store the image from the camera.

<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="https://habr.com/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="https://habr.com/ru/company/otus/blog/725382/./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <HelloWorld msg="Vite + Vue + Ionic Capacitor" />
  <button @click="showActionSheet" class="action-button">SHOW ACTION SHEET</button>
  <button @click="takePicture"  class="action-button">TAKE PICTURE</button>
  <img :src="https://habr.com/ru/company/otus/blog/725382/imageUrl" style="width: 100%"/>
</template>

Read more…

You can view the entire list of Ionic Capacitor plugins Hereand for more information about Ionic PWA plugins – Here.


3. How to Build a Mobile App with Vite, Vue and Ionic Capacitor – Adding Firebase and Firebase Emulator to Project

Welcome to our integration blog firebase emulator with your project Vite, Vue! This post is in addition to our video on the same topic, which you can find at the link below.

If you are having difficulty testing and iterating on your project firebase, constantly forced to switch to a “live” environment (real operating conditions) to see their changes, then you are in luck! In this post, we will show you how to integrate the Firebase emulator into your Vite, Vue project using Ionic Capacitorwhich will give you the ability to test, iterate, and reset data without leaving your local machine.

We’ll walk you through the entire process step by step, with a video of the terminal commands and source code so you can follow along and see exactly how it’s done. But that’s not all – this post is part of an ongoing series on integrating Firebase with Vite, a Vue project. In the following videos, we will show you how to fully integrate Firebase with vue firea library that provides seamless Firebase integration with Vue.js apps.

So, if you’re ready to take your Firebase project to the next level and streamline your development process, be sure to watch our video and read this post!

Install NPM packages

npm install -g firebase-tools
npm install firebase

Login to your Firebase account

firebase login

Initialize the local Firebase emulator

firebase init

sample output

aaronksaunders@Aarons1ProM1Pro vite-vue-cap % firebase init                              

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  /Users/aaronksaunders/develop/projects/vite-vue-cap

? Which Firebase features do you want to set up for this directory? Press Space to select 
features, then Enter to confirm your choices. Emulators: Set up local emulators for Firebase 
products

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add, 
but for now we'll just set up a default project.

? Please select an option: Create a new project
i  If you want to create a project in a Google Cloud organization or folder, please use "firebase projects:create" instead, and return to this command when you've created the project.
? Please specify a unique project id (warning: cannot be modified afterward) [6-30 characters]:
 testem1
? What would you like to call your project? (defaults to your project ID) 
✔ Creating Google Cloud Platform project
✔ Adding Firebase resources to Google Cloud Platform project

🎉🎉🎉 Your Firebase project is ready! 🎉🎉🎉

Project information:
   - Project ID: testem1
   - Project Name: testem1

Firebase console is available at
https://console.firebase.google.com/project/testem1/overview
i  Using project testem1 (testem1)

=== Emulators Setup
? Which Firebase emulators do you want to set up? Press Space to select emulators, then Enter to 
confirm your choices. Authentication Emulator, Firestore Emulator
? Which port do you want to use for the auth emulator? 9099
? Which port do you want to use for the firestore emulator? 8080
? Would you like to enable the Emulator UI? Yes
? Which port do you want to use for the Emulator UI (leave empty to use any available port)? 
? Would you like to download the emulators now? Yes
i  ui: downloading ui-v1.11.4.zip...

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

✔  Firebase initialization complete!

Launch the emulator

firebase emulators:start

sample output

aaronksaunders@Aarons1ProM1Pro vite-vue-cap % firebase emulators:start
i  emulators: Starting emulators: auth, firestore
⚠  firestore: Did not find a Cloud Firestore rules file specified in a firebase.json config file.
⚠  firestore: The emulator will default to allowing all reads and writes. Learn more about this option: https://firebase.google.com/docs/emulator-suite/install_and_configure#security_rules_configuration.
i  firestore: Firestore Emulator logging to firestore-debug.log
✔  firestore: Firestore Emulator UI websocket is running on 9150.
i  ui: downloading ui-v1.11.4.zip...
Progress: =========================================================================> (100% of 4MB)
i  ui: Removing outdated emulator files: ui-v1.6.5
i  ui: Removing outdated emulator files: ui-v1.6.5.zip
i  ui: Emulator UI logging to ui-debug.log

┌─────────────────────────────────────────────────────────────┐
│ ✔  All emulators ready! It is now safe to connect your app. │
│ i  View Emulator UI at http://127.0.0.1:4000/               │
└─────────────────────────────────────────────────────────────┘

┌────────────────┬────────────────┬─────────────────────────────────┐
│ Emulator       │ Host:Port      │ View in Emulator UI             │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Authentication │ 127.0.0.1:9099 │ http://127.0.0.1:4000/auth      │
├────────────────┼────────────────┼─────────────────────────────────┤
│ Firestore      │ 127.0.0.1:8080 │ http://127.0.0.1:4000/firestore │
└────────────────┴────────────────┴─────────────────────────────────┘
  Emulator Hub running at 127.0.0.1:4400
  Other reserved ports: 4500, 9150

Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.

Video code

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { IonicVue } from "@ionic/vue";

/* Core CSS required for Ionic components to work properly */
import "@ionic/vue/css/core.css";

/* Basic CSS for apps built with Ionic */
import "@ionic/vue/css/normalize.css";
import "@ionic/vue/css/structure.css";
import "@ionic/vue/css/typography.css";

/* Optional CSS utils that can be commented out */
import "@ionic/vue/css/padding.css";
import "@ionic/vue/css/float-elements.css";
import "@ionic/vue/css/text-alignment.css";
import "@ionic/vue/css/text-transformation.css";
import "@ionic/vue/css/flex-utils.css";
import "@ionic/vue/css/display.css";

/* Theme variables */
// import './theme/variables.css';

import router from "./router";
import { initializeApp } from "firebase/app";
import {
  getFirestore,
  collection,
  addDoc,
  connectFirestoreEmulator,
  serverTimestamp,
  query,
  getDocs,
  orderBy,
} from "firebase/firestore";

const firebaseApp = initializeApp({
  projectId: "testem1",
});

console.log("firebaseApp", firebaseApp);

// used for the firestore
export const db = getFirestore(firebaseApp);
console.log("firestore database", db);

// connect the application to the emulator
if (location.hostname === "localhost") {
  // Point to the Storage emulator running on localhost.
  connectFirestoreEmulator(db, "localhost", 8080);
}

(async () => {
  try {
    // write a document to database...
    const docRef = await addDoc(collection(db, "stuff"), {
      name: "aaron",
      created_at: serverTimestamp(),
    });
    console.log("new document", docRef);

    // get all of the documents
    const queryResult = await getDocs(
      query(collection(db, "stuff"), orderBy("created_at", "asc"))
    );

    // display to console
    const dataArray = queryResult.docs.map((d) => {
      return { name: d.data().name, when: d.data().created_at.toDate() };
    });
    console.log("queryResult", dataArray);
  } catch (e) {
    console.log(e);
  }
})();

const app = createApp(App).use(IonicVue).use(router);

router.isReady().then(() => {
  app.mount("#app");
});

4. How to Build a Mobile App with Vite, Vue and Ionic Capacitor – Firebase SignIn and SignOut with Firebase Authentication Emulator

IN previous video we have installed and configured the firebase emulator for firebase firestore. In this video tutorial we will show you how to integrate firebase Authentication (authentication) in the mobile application Vite, Vue and Ionic Capacitor. You’ll learn how to set up Firebase Authentication and the Firebase Authentication emulator to secure access to your app’s collections. We will also demonstrate how to use a router to create an application flow that requires users to authorize before accessing secure pages.

In particular, you will learn:

  • How to add Firebase Authentication to Vite, Vue and Ionic Capacitor mobile app.

  • How to create basic firebase rules to only allow authorized users to access collections

  • How to use a router to create an application flow that requires user authentication

  • How to redirect users to the registration page when trying to access secure pages without authentication

If you are new to mobile development or already have experience with Vue and Ionic Capacitor; this tutorial is perfect for anyone looking to add Firebase Authentication to their mobile app.

I already used firebase before and it’s amazing! The emulator makes it much easier to quickly iterate, test, and reset everything on your local machine.

This is just the next step towards fully integrating Firebase, VueFire and Pinia in the next videos in this series.

Firebase Local Emulator Suite can be installed and configured for a variety of prototyping and test environments, from one-off prototyping sessions to industrial-scale continuous integration workflows.

Ionic Capacitor is an open source native runtime for building native web applications. Build cross-platform iOS, Android, and Progressive Web Apps with JavaScript, HTML, and CSS.

Vite is a build tool that aims to enable faster and easier development of modern web projects. It consists of two main parts: the dev (development) server, which provides advanced features compared to native ES modules, such as ultra-fast hot module replacement (HMR), and the build (build) command, which merges your code with Rollup, pre configured to output highly optimized static assets for production.

Series playlist: YouTube playlist


Vite.js is one of the tools for setting up development environments. Vite is suitable for complex projects where interaction with the server is required. Unlike many other auxiliary tools, Vite is easily embedded through the terminal and can be quickly deployed when needed.

Vite Benefits:
– Almost instant development server startup time.
– Hot-swappable modules out of the box.
– Simple configuration.
– Support for ES modules out of the box.

How to migrate from Vue CLI to Vite? We will discuss this in an open lesson. Sign up on the page of the online course “Vue.js Developer”.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *