Modern web applications often require native device features such as camera access, geolocation, and file storage. Capacitor is a popular open-source framework that enables developers to build cross-platform apps using web technologies while accessing native device capabilities. This step-by-step guide will walk you through setting up Capacitor for your modern web app.

Prerequisites

  • Node.js installed on your machine
  • Basic knowledge of JavaScript and web development
  • An existing web application or project folder
  • Package manager like npm or yarn

Step 1: Initialize Your Web Project

If you haven't already, create your web project or navigate to your existing project directory. For example:

mkdir my-web-app

cd my-web-app

Initialize your project with npm:

npm init -y

Install necessary dependencies like Capacitor:

npm install @capacitor/core @capacitor/cli

Step 2: Initialize Capacitor in Your Project

Run the following command to initialize Capacitor and set up the configuration:

npx cap init

You will be prompted to enter your app name and package ID (e.g., com.example.app). Provide appropriate values.

Step 3: Add Platforms

Capacitor supports multiple platforms like Android and iOS. To add a platform, run:

npx cap add android

or

npx cap add ios

Step 4: Build Your Web App

Ensure your web app is built and ready to be integrated into native platforms. For example, if you are using React, run:

npm run build

Step 5: Copy Web Assets to Native Projects

Copy the built web assets into the native projects with the following command:

npx cap copy

Step 6: Open Native IDEs and Run

Open the native project in Android Studio or Xcode:

For Android:

npx cap open android

For iOS:

npx cap open ios

Build and run your app from the IDE to test native features.

Step 7: Use Capacitor Plugins

Capacitor provides plugins to access native device features. Install plugins as needed:

npm install @capacitor/geolocation

Then, import and use the plugin in your JavaScript code:

import { Geolocation } from '@capacitor/geolocation';

Example usage:

const position = await Geolocation.getCurrentPosition();

Conclusion

Setting up Capacitor allows you to develop modern web apps with native device capabilities. Follow these steps to integrate Capacitor into your project, add platforms, and start building hybrid applications that deliver native-like experiences across devices.