Getting Started with Capacitor
This lesson is going to focus on the basics of getting set up with Capacitor, which will include:
- Installation
- Adding native platforms
- Syncing your web code with the native application
- Running native builds
NOTE: If you are using Ionic and VS Code, then I highly recommend downloading the Ionic VS Code extension. This provides you with a GUI interface directly in your editor that you can use to perform common Capacitor operations like running on native devices, and it will also automatically detect potential problems for you. If you are not overly familiar with the Capacitor commands you need to run, this can be a great help.
Installing Capacitor
If you’re using Ionic, then your project likely already has Capacitor installed - it’s installed by default when you generate a new Ionic application. However if you are not using Ionic, as long as your application has:
- A
package.json
file - A directory where your built web application is output (e.g. a
dist
, orpublic
, orwww
folder) - An
index.html
file at the root of your built output
Then you can use Capacitor. The general idea here is that we need to be able to install Capacitor, and Capacitor needs to know where to find the built web output that it can copy into the native applications web view.
To install Capacitor, you will need to run the following commands:
npm i @capacitor/core
npm i -D @capacitor/cli
NOTE: This is only for non-Ionic applications. You generally don’t need to set Capacitor up for Ionic applications, it is done for you.
After installing these packages, you can configure Capacitor for your project by running:
npx cap init
If you are using Ionic, and for some reason your Ionic application does not already have Capacitor installed, you can easily install and configure it by running:
ionic integrations enable capacitor
Adding Native Platforms
By default, no native platforms will be added by Capacitor (i.e. no native iOS/Android application will be created within your project). To do this (if you are not using Ionic) you will first need to add the package for the native platform you want to target (or both of them):
npm install @capacitor/android
npm install @capacitor/ios
Then you can create the native platforms within your project by running:
npx cap add android
npx cap add ios
If you are using Ionic, then you can use the Ionic CLI to do this all for you by running: