Capacitor, Ionic's new native API container aimed at creating iOS, Android, and Web apps using JavaScript, hit version 1.0. It attempts to bring a new take on how to build cross-platform apps that access native features.
Similarly to Cordova, Capacitor's goal is to make it possible to access native features of the OS underlying an app without requiring to write platform-specific code. This makes possible to use, for example, the device camera via the same code in iOS, Android, and Electron apps. Capacitor, though, takes a radically different approach to containerize an HTML/CSS/JavaScript app to run it in a native Web View and expose native functionality your app can use through a unified interface.
One major difference comparted to Cordova is that Capacitor requires developers to handle their native app project, the part that includes the Web View where the Ionic app is run, as a component of the Capacitor app rather than the opposite. This approach makes it easier to integrate external SDKs that may require tweaking the AppDelegate on iOS, as well as to integrate native functionality to the Ionic app without writing a proper plugin, as it was the case with Cordova.
Another benefit of Capacitor is it does not require you to listen to the deviceready event anymore. This is made possible by Capacitor loading all plugins before the Ionic app is loaded, so they are immediately available. Additionally, Capacitor plugins expose callable methods, so you do not need to use exec
. For example, this is a very simple Capacitor plugin for iOS, a Swift class extending CAPPlugin
:
import Capacitor
@objc(MyPlugin)
public class MyPlugin: CAPPlugin {
@objc func echo(_ call: CAPPluginCall) {
let value = call.getString("value") ?? ""
call.resolve([
"value": value
])
}
}
To make the plugin echo
method directly available to the Capacitor web runtime, you need to register it in a .m
file:
#import <Capacitor/Capacitor.h>
CAP_PLUGIN(MyPlugin, "MyPlugin",
CAP_PLUGIN_METHOD(echo, CAPPluginReturnPromise);
)
Capacitor uses npm for its dependency management, including plugins and platforms. So, when you need to use a plugin, you just run npm install
as usual for JavaScript project. With Cordova, instead, you are required to use the cordova plugin add ...
command. As an added simplification, Capacitor requires the native component of iOS plugins to be packaged as a CocoaPod, and for Android as a standalone library.
As a final note, Capacitor will eventually replace Cordova as the official way to containerize Ionic apps so they can access native features cross-platform, but Cordova will be supported for many years to come, Ionic says.