Ionic capacitor

From j4flmao/agent-skills · View interactive version

Ionic capacitor is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about Ionic, Capacitor, Capacitor plugins, Ionic React/Angular/Vue, hybrid web-to-mobile apps or live updates for a Capacitor app. Produces hybrid app setup, native plugin bridges and store builds. Not for fully native or shared-Kotlin apps (use mobile-kotlin-multiplatform) or

How to use this skill

Skill file

Mobile Ionic & Capacitor

Purpose

Guide for building hybrid mobile apps with Ionic framework and Capacitor native bridge.

Agent Protocol

Trigger

Phrases: "Ionic", "Capacitor", "Ionic app", "hybrid mobile", "web-to-mobile", "Capacitor plugin", "Ionic framework", "Ionic React", "Ionic Angular", "Ionic Vue"

Input Context

Output Artifact

Ionic project with: Capacitor config, native plugin integrations, custom plugin code, build/deploy pipeline scripts.

Response Format

<ionic-capacitor>
<project>{framework, capacitor config, structure}</project>
<plugins>{installed plugins, config, permissions}</plugins>
<custom-plugin>{swift/kotlin, call pattern}</custom-plugin>
<build>{sync, xcode, android-studio steps}</build>
</ionic-capacitor>

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

Max Response Length

8000 tokens

Architecture

Hybrid Bridge Architecture

┌─────────────────────────────────────────────┐
│           Web Application (SPA)              │
│  Ionic UI Components | Framework (React/     │
│  Angular/Vue) | App Logic                    │
└──────────────────┬──────────────────────────┘
                   │
┌──────────────────▼──────────────────────────┐
│          Capacitor Bridge (WKWebView/        │
│          Android WebView)                    │
│  • Plugin registry: maps JS calls to native  │
│  • JSON serialization/deserialization        │
│  • Error propagation via Promise reject      │
│  • Event emitter for native-to-JS events     │
└───────┬─────────────────────┬───────────────┘
        │                     │
┌───────▼─────────┐  ┌───────▼───────────────┐
│   iOS Runtime    │  │   Android Runtime      │
│   (Swift/Obj-C)  │  │   (Kotlin/Java)        │
│   CAPPlugin      │  │   CAPPlugin            │
└─────────────────┘  └───────────────────────┘

Decision Tree: Framework Selection

Team expertise?
├── React developers → Ionic React
│   Pros: hooks, largest ecosystem, TypeScript-first
│   Cons: routing less mature than Angular
├── Angular developers → Ionic Angular
│   Pros: mature routing (lazy loading, guards), full-featured
│   Cons: more boilerplate, steeper learning curve for new devs
└── Vue developers → Ionic Vue
    Pros: lightweight, composition API, growing ecosystem
    Cons: fewer community plugins, smaller talent pool

Decision Tree: Plugin Strategy

Need native device access?
├── Common feature (camera, geolocation, storage)
│   → Use official @capacitor/* plugin
│   → Configure permissions in native project files
├── Niche but exists (bluetooth, NFC, health kit)
│   → Search npm for @capacitor-community/* or capacitor-*
│   → Evaluate maintenance status, open issues, last update
├── Existing Cordova plugin
│   → Use @capacitor/cordova-plugin-compat
│   → Test thoroughly — not all Cordova patterns migrate cleanly
└── Completely custom native requirement
    → Write custom plugin (Swift + Kotlin)
    → Keep plugin surface small, test on real device

Workflow

  1. Ionic framework overview — Ionic is a UI toolkit for building cross-platform mobile apps using web technologies (HTML, CSS, JS). It provides a library of mobile-optimized UI components (ion-*), gestures, and animations that mimic native platform conventions. Three framework integrations: Ionic React (hooks, fast iteration, largest ecosystem), Ionic Angular (NgModule + standalone, mature routing, full-featured), Ionic Vue (composition API, lightweight, growing ecosystem). All share @ionic/core components and CSS custom properties theming.
  1. Capacitor vs Cordova — Capacitor is the successor to Cordova with key advantages: modern plugin API (Promise-based instead of callback), native project files committed to repo (full Xcode/Android Studio control), Swift/Kotlin plugin development (instead of Java/Obj-C), HMR support during development, PWA fallback for web, and unified config (capacitor.config.ts). Cordova plugins are compatible via @capacitor/cordova-plugin-compat. Migration path: npx cap init on existing Cordova project, then replace cordova plugin add with npm install @capacitor/plugin-name.
  1. Project creation — ionic start myApp blank --type=react-ts creates an Ionic React TypeScript project with Capacitor pre-configured. Key files: capacitor.config.ts (app ID, name, server URL for live reload), ionic.config.json (project type, integrations), src/ (web app code), ios/ (Xcode project after npx cap add ios), android/ (Android Studio project after npx cap add android). The web app is the single source of truth — native projects are generated artifacts.
  1. Live reload development — ionic serve for web-only HMR. For device live reload: ionic cap run ios -l --external starts a dev server with your machine's IP, updates capacitor.config.ts with server.url, then opens Xcode. The device loads web assets from the dev server over the network. Hot Module Replacement preserves component state. For Android: ionic cap run android -l --external. Requires device on same network as dev machine. Disable server.url for production builds.
  1. Capacitor plugin system — Plugins are npm packages that expose native APIs to JavaScript. Architecture: TypeScript API definition (@capacitor/plugin-name) -> iOS implementation (Swift, CAPPlugin subclass) -> Android implementation (Kotlin, CAPPlugin subclass) -> optional web fallback. Plugin calls are serialized via JSON through the WebView bridge. npx cap sync installs plugin pods (iOS) and copies plugin code (Android). Permissions must be configured in native project files before plugin use.
  1. PWA conversion — Capacitor apps are PWAs by default. The same web code works as a standalone PWA when served over HTTPS. Add a manifest.json with icons, service-worker.js for caching. Capacitor plugins gracefully degrade: check Capacitor.isPluginAvailable('Camera') before calling native APIs. PWA mode runs in the browser, not WebView. Use @capacitor/filesystem and @capacitor/storage as they have web fallbacks.
  1. Build and deploy pipeline — ionic build --prod generates optimized web assets in www/. npx cap copy copies to native platforms, npx cap sync also installs native dependencies. Code signing: iOS via Xcode Automatic signing (requires Apple Developer account), Android via keystore (keytool -genkey then ./gradlew bundleRelease). Distribution: App Store Connect (iOS) via Xcode Organizer or Transporter, Google Play Console (Android) via signed AAB upload. Appflow and EAS Build for cloud CI/CD.
  1. Custom plugin development — When an official plugin does not exist, create a custom plugin. Structure: npx cap plugin:generate my-plugin scaffolds the plugin template. The generated plugin has src/definitions.ts (TypeScript interface), src/web.ts (web fallback), ios/Plugin/Plugin.swift (iOS native), android/src/main/.../Plugin.kt (Android native). Implement @objc annotated methods on iOS and @PluginMethod annotated methods on Android. Return data via call.resolve() and errors via call.reject(). Test the plugin in a sample Ionic app before publishing.
  1. Deep linking and universal links — Configure deep links to open the app from URLs. iOS: configure apple-app-site-association file on your server, add associated domain in Xcode, handle in AppDelegate. Android: configure intent filters in AndroidManifest.xml for URL scheme. Capacitor's App.addListener('appUrlOpen') catches incoming URLs in the web layer. Map URL paths to navigation routes. Test with xcrun simctl openurl for iOS and adb shell am start for Android.
  1. Push notifications — Set up push notifications via @capacitor/push-notifications. iOS: configure APNs certificate in Apple Developer Portal, add Push Notifications capability in Xcode. Android: add the app to a Firebase project and include google-services.json; your server sends through the FCM HTTP v1 API with a service-account OAuth token (legacy server keys were shut down in 2024). Register for notifications: PushNotifications.requestPermissions() then PushNotifications.register(). Handle foreground notifications with PushNotifications.addListener('pushNotificationReceived'). Handle background tap actions with PushNotifications.addListener('pushNotificationActionPerformed'). Test with curl to APNs/FCM endpoints or use Pusher/PushCompanion tools.

Platform Compatibility

| Feature | iOS | Android | Web/PWA |

|---------|-----|---------|---------|

| Core UI components | Full | Full | Full |

| Native plugins | All | All | Graceful fallback |

| Push notifications | APNs | FCM | Not supported |

| Background mode | Limited | Yes | Not supported |

| Live reload | Yes | Yes | Dev only |

| HMR | Via server | Via server | Built-in |

| Camera access | Full | Full | Browser limited |

| Geolocation | Full | Full | Browser limited |

| Biometric auth | Face ID/Touch ID | Fingerprint/Biometric | Not supported |

| File system | Full | Full | Sandboxed |

Best Practices

Common Pitfalls

Compared With

| Approach | Use Case | Tradeoff |

|----------|----------|----------|

| Ionic + Capacitor | Hybrid apps, web-to-mobile migration | WebView performance ceiling, native API gap |

| React Native | Near-native perf, large ecosystem | Separate RN component lib, thicker bridge |

| Flutter | High-performance cross-platform | Dart language, custom rendering engine |

| Kotlin Multiplatform | Native UI, shared logic | Two UI codebases, less mature |

| MAUI (.NET) | .NET ecosystem, enterprise | Windows-focused, smaller mobile community |

| Pure PWA | No app store, instant updates | Limited device API access, no push on iOS |

| Native (Swift/Kotlin) | Full platform access | Two codebases, higher maintenance cost |

Performance

Tooling

| Tool | Category | Purpose |

|------|----------|---------|

| Ionic CLI | Project management | Start, build, serve, cap commands |

| Capacitor CLI | Native bridge management | Add platforms, sync, copy, open |

| Appflow | CI/CD | Cloud build, live deploy, package |

| EAS Build (Expo) | CI/CD alternative | Cloud builds for Capacitor apps |

| capacitor-assets | Asset generation | Auto-generate icons and splash screens |

| Portals (Ionic) | Micro-frontends | Embed web apps in native apps |

| Cordova Plugin Compat | Migration | Run Cordova plugins in Capacitor |

| Safari Web Inspector | Debugging | iOS WebView JS console, network, elements |

| Chrome DevTools | Debugging | Android WebView JS console, network, elements |

| xcodebuild / Gradle | Native build | Platform-specific compilation and signing |

| fastlane | Automation | Certificate management, beta deployment, screenshots |

| Maestro / Detox | E2E testing | Mobile UI testing for hybrid apps |

Configuration Reference

// capacitor.config.ts
import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'MyApp',
  webDir: 'www',
  server: {
    url: process.env.NODE_ENV === 'development' ? 'http://192.168.1.100:8100' : undefined,
    cleartext: true,
  },
  plugins: {
    SplashScreen: {
      launchShowDuration: 3000,
      backgroundColor: '#ffffff',
    },
    PushNotifications: {
      presentationOptions: ['badge', 'sound', 'alert'],
    },
  },
  ios: { contentInset: 'always' },
  android: { allowMixedContent: true },
};
export default config;

Rules

Performance Optimization

WebView Rendering Performance

The WebView is the bottleneck in Ionic apps. Optimize for 60fps scrolling and smooth animations:

JavaScript Bundle Optimization

Native Bridge Optimization

```typescript

import { NgZone } from '@angular/core';

constructor(private zone: NgZone) {}

async callPlugin() {

const result = await this.zone.runOutsideAngular(() => Camera.getPhoto({...}));

// Re-enter zone only for UI updates

}

```

Memory and Caching

Production Build & App Store Deployment

Android Play Store

  1. Build signed AAB: ionic build --prod && npx cap sync android && cd android && ./gradlew bundleRelease
  2. Signing: Configure android/app/build.gradle signing configs:

```groovy

android {

signingConfigs {

release {

storeFile file(System.getenv("KEYSTORE_PATH"))

storePassword System.getenv("KEYSTORE_PASS")

keyAlias System.getenv("KEY_ALIAS")

keyPassword System.getenv("KEY_PASS")

}

}

buildTypes {

release { signingConfig signingConfigs.release }

}

}

```

  1. Play Console: Upload AAB → Set up Store Listing (screenshots, description, category) → Content Rating → Pricing & Distribution → Rollout to Internal Testing → Closed Alpha → Open Beta → Production.
  2. App signing by Google Play: Enroll in Play App Signing. Google manages the signing key; you upload an upload key. If you lose the upload key, Google can reset it.

iOS App Store

  1. Build IPA: ionic build --prod && npx cap sync ios && cd ios && xcodebuild -workspace App.xcworkspace -scheme App -archivePath App.xcarchive archive
  2. Code signing: Automatic signing in Xcode (requires Apple Developer account). For CI, use fastlane match to manage certificates and provisioning profiles across machines.
  3. App Store Connect: Create app record → Upload IPA via Transporter or Xcode Organizer → Fill out metadata (name, description, keywords, privacy URL) → Submit for Review.
  4. TestFlight: Enable in App Store Connect → Add testers (up to 100 internal, 10,000 external) → Build must pass basic review before external testing. Beta builds expire after 90 days.

Fastlane Automation

# fastlane/Fastfile
lane :deploy_ios do
  match(type: "appstore")  # sync certificates
  build_ios_app(scheme: "App")
  upload_to_app_store(skip_metadata: true, skip_screenshots: true)
end

lane :deploy_android do
  gradle(task: "bundleRelease")
  upload_to_play_store(track: "internal")
end

Environment Configuration

```typescript

// src/environments/environment.prod.ts

export const environment = {

production: true,

apiUrl: 'https://api.example.com',

appVersion: '1.2.3',

};

```

Custom Plugin Code Examples

iOS (Swift) — Background Geolocation Plugin

@objc(BackgroundGeolocation)
class BackgroundGeolocation: CAPPlugin {
    private var locationManager = CLLocationManager()

    @objc func startTracking(_ call: CAPPluginCall) {
        locationManager.delegate = self
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.startUpdatingLocation()
        call.resolve()
    }

    @objc func stopTracking(_ call: CAPPluginCall) {
        locationManager.stopUpdatingLocation()
        call.resolve()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        notifyListeners("locationUpdate", data: [
            "latitude": location.coordinate.latitude,
            "longitude": location.coordinate.longitude,
            "accuracy": location.horizontalAccuracy
        ])
    }
}

Android (Kotlin) — Same Plugin

@CapacitorPlugin(name = "BackgroundGeolocation")
class BackgroundGeolocation : CAPPlugin() {
    private val locationManager by lazy {
        activity?.getSystemService(Context.LOCATION_SERVICE) as? LocationManager
    }

    @PluginMethod
    fun startTracking(call: PluginCall) {
        if (ActivityCompat.checkSelfPermission(
                activity, Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            call.reject("Location permission not granted")
            return
        }
        locationManager?.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 5000L, 10f,
            object : LocationListener {
                override fun onLocationChanged(location: Location) {
                    notifyListeners("locationUpdate", JSObject().apply {
                        put("latitude", location.latitude)
                        put("longitude", location.longitude)
                        put("accuracy", location.accuracy)
                    })
                }
            }
        )
        call.resolve()
    }

    @PluginMethod
    fun stopTracking(call: PluginCall) {
        locationManager?.removeUpdates(this)
        call.resolve()
    }
}

Web Fallback

// src/web.ts
import { WebPlugin } from '@capacitor/core';
import type { BackgroundGeolocationPlugin } from './definitions';

export class BackgroundGeolocationWeb
  extends WebPlugin
  implements BackgroundGeolocationPlugin
{
  async startTracking(): Promise<void> {
    console.warn('BackgroundGeolocation not available on web');
    // Fallback: use browser Geolocation API
    navigator.geolocation.watchPosition(
      (pos) => this.notifyListeners('locationUpdate', {
        latitude: pos.coords.latitude,
        longitude: pos.coords.longitude,
        accuracy: pos.coords.accuracy,
      }),
      (err) => console.error(err),
      { enableHighAccuracy: true, timeout: 10000 }
    );
  }

  async stopTracking(): Promise<void> {
    // cleanup
  }
}

Plugin Testing

References

Handoff

Hand off to native iOS/Android skills when custom plugin development needs deep platform API access beyond Capacitor's bridge.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.