Skip to content
View lessons Login

Launch sale! Get 30% OFF expires in 126:46:24

3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Creating a Publishable Capacitor Plugin

Creating a Publishable Capacitor Plugin

When integrating custom native code we have mostly been focusing on adding that code directly to our local native projects. However, you might also want to build and publish a plugin that is installable just like any other official plugin or the community plugins. This is great for if you want to share your plugin with the world, or if you just want to be able to easily install it in multiple different projects without having to manually configure code every time.

As an added bonus, with publishable plugins you don’t need to worry about setting up your own custom view controller.

In this lesson, we are going to cover how you can create a publishable plugin.

Generate a new Plugin

To generate a new Capacitor plugin as its own project we can run the following command:

npm init @capacitor/plugin

This will prompt you for what you want the name of your package to be (e.g. the name you would use with the npm install command). We will use our AlertPlugin as an example, so maybe we would name it capacitor-alert-plugin.

You will eventually get to a prompt asking you for the Class name, you might use something like Alert for this but it doesn’t really matter. It will also make you supply a repo URL, you can just enter a fake value here for now or where you expect to create the GitHub URL, e.g:

https://github.com/your-username/capacitor-alert-plugin

Make your way through the rest of the prompts, and then your plugin should be generated.

Implementing the Plugin

The great thing about this generate command is that it does so much for you

  • almost everything is completely set up and if you are just creating a simple plug in it is really easy to drop in your code.

Let’s walk through the steps required to add our basic AlertPlugin functionality to this project we just created.

export interface AlertPlugin {
present(options: { message: string }): void;
}

This is the interface we will use in our application to interact with the plugin, and it is the same approach that we have already been using for our local plugins.

import { WebPlugin } from '@capacitor/core';
import type { AlertPlugin } from './definitions';
export class AlertWeb extends WebPlugin implements AlertPlugin {
present(options: { message: string }): void {
console.log(options.message);
}
}
EXTENDED EXTENDED

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).