Working With Capacitor

Learn how to use the command line to add and use Capacitor plugins within an Ionic project.

Adding Capacitor to a project

Capacitor can be added to an existing frontend project or by starting a new project.

To add Capacitor to an existing non-Ionic frontend project, we simply need to run the following from the command line:

cd name-of-project-directory-here
npm install @capacitor/core @capacitor/cli --save-dev

Note: Your frontend project must have a valid package.json file and a <head> element within the project’s main index.html file, as this will be used to inject Capacitor into upon app initialization.

Once installed, Capacitor needs to be initialized with information about the application with the following command:

npx cap init

This command then prompts us to enter the name of the application and the app ID (the bundle identifier for iOS and the package name for Android). The --web-dir flag can also be used to set the web assets directory (the default is www), if desired.

Finally, the following native platforms (depending on which we want to target) can be used within our project:

npm install @capacitor/android
npx cap add android
npm install @capacitor/ios
npx cap add ios

Now Capacitor is installed, ...