Pacharapol Withayasakpunt Pacharapol Withayasakpunt
Thu 8 August 2019
Cordova, TypeScript, Vue and using features beyond WebView

Cordova, TypeScript, Vue and using features beyond WebView

An easy way to set a layout for mobile apps, easier than Flutter, React Native or NativeScript, for instance, is to use Apache Cordova or PhoneGap. This is probably due to CSS/SCSS/HTML (rather than partial CSS support in NativeScript).

Why Vue? Because Vue's Vuetify's Material design looks just like Android! While being easier to set the layout than NativeScript Vue.

An example app I have used all the above-mentioned in the header is

patarapolw/nltkpass-app

patarapolw/nltkpass-app

Mobile application for NLTKPass. Contribute to patarapolw/nltkpass-app development by creating an account on GitHub.

Since I use both Vue-CLI and Apache Cordova, there are two ways to do this.

With Vue-CLI it is fairly easy to set up like this (with just an extra vue add pug)

<template lang="pug">
</template>

<script lang="ts">
</script>

<style lang="scss">
</style>

What feature do I need beyond WebView? I need file server, because a data text file I used is fairly large (20 MB), and Vue-CLI's Webpack wouldn't compile!.

fetch() do work in cordova run browser, but not in cordova run android; so I have to create a custom script.

// cordova.ts
export async function fetchText(path: string): Promise<string> {
  if ((window as any).cordova && cordova.file) {
    return new Promise((resolve, reject) => {
      (window as any).resolveLocalFileSystemURL(`${cordova.file.applicationDirectory}www/${path}`,
      (fileEntry: any) => {
        fileEntry.file((f: any) => {
          const reader = new FileReader();
          reader.onloadend = function() {
            resolve(this.result as string);
          }
          reader.readAsText(f);
        })
      },
      (e: any) => reject(e));
    })
  } else {
    return (await fetch(path)).text();
  }
}

This way, when I use fetchText, instead of await fetch, it will work for Android.

In my next projects, I would undoubtedly use SQLite, and fetch data from API from an online web server...

What worries me after this point, is how do I access native Android API from Cordova... It might not be as easy as Flutter?