Capacitor: Running a Web App on Mobile

March 05, 2019 0 Comments

Capacitor: Running a Web App on Mobile

 

 

Capacitor, a project built by the team behind Ionic, is a great way to take your JavaScript web applications and get them running on iOS, Android, desktop (via Electron) or the web platform. It allows you to access the native device’s SDKs and aims to be a replacement for Cordova. I’ll be assuming that we have an Ionic application built with Create React App (yes, you read that right!) for this article, but your implementation may be different.

Firstly, let’s build our application so that our production build can be ran on a device:

Next, to install Capacitor, run the following in your terminal inside of your project folder to install the needed packages:

$ npm install --save @capacitor/core @capacitor/cli $ npx cap init 

You’ll then be asked some information about your project. As this is project is simply an example, use the defaults for each prompt.

We’ll then be greeted with something similar to this:

🎉 Your Capacitor project is ready to go! 🎉 Add platforms using "npx cap add": npx cap add android npx cap add ios npx cap add electron 

From here we can select the project we’d like to build to. I’ll be using ios for my example.

Uh oh, running this with the default settings gives us this error!

[error] Capacitor could not find the web assets directory "/repos/ionic-react/www". Please create it, and make sure it has an index.html file. You can change the path of this directory in capacitor.config.json. More info: https://capacitor.ionicframework.com/docs/basics/configuring-your-app 

This is a common error you may run into when adding Capacitor to a new Ionic project. Let’s update the newly created capacitor.config.json to point toward the build directory:

{ "appId": "com.example.app", "appName": "App", "bundledWebRuntime": false, "webDir": "build" 
}

If we run the command again, Capacitor will add an iOS application to our project which we can open inside of Xcode with:

We can open our application on a device by clicking the Play button from within Xcode.

Making Changes to the App

As we continue to develop our application, we don’t want to have to remove the platform folder and re-add it each time. Luckily, we can build our JavaScript and copy the files over to our iOS project by using cap copy:

$ npm run build $ npx cap copy 

This will use the files inside of our build folder to update our build. If we restart our application from within Xcode again, you’ll see that the application updates with any changes you’ve made.

And that’s it! Now that you’re up and running with Capacitor, you can checkout the official documentation to learn about plugins and how to use the different device SDKs or web APIs. Stay tuned for more Capacitor content coming soon. 👍


Tag cloud