Zum Hauptinhalt springen
Tutorial

Erstelle eine Next.js-Mobil-App von Grund auf mit Capacitor 8

Schritt-für-Schritt-Anleitung zur Erstellung einer neuen Next.js 15-Projekt und Umwandlung in native iOS- und Android-Mobil-Apps mit Capacitor 8. Perfekt für das Starten von frischen mobile-first-Entwicklungen.

Martin Donadieu

Martin Donadieu

Content Marketer

Ein Next.js-Mobil-App von Grund auf mit Capacitor erstellen

Einleitung

Möchten Sie eine mobile App mit Next.js von vorne herein erstellen? Diese Anleitung führt Sie durch die Erstellung einer brandneuen Next.js 15-Projekt, das von Anfang an für Mobilgeräte konfiguriert ist, und das dann als native iOS- und Android-Apps verpackt wird. Capacitor 8.

Am Ende dieser Anleitung haben Sie eine funktionierende mobile App, die auf Simulatoren läuft, die Sie weiterentwickeln und schließlich auf die App Store und Google Play veröffentlichen können.

Zeitaufwand: ~30 Minuten

Was Sie bauen werden:

  • Ein neues Next.js 15-Projekt mit App Router
  • Statistische Exportkonfiguration für Mobilgeräte
  • Capacitor 8 mit wichtigen Plugins
  • Nativ-Apps für iOS und Android
  • Entwicklungssetup mit Live-Reload

Haben Sie bereits eine Next.js App? Überprüfen Sie Konvertieren Sie Ihre Next.js App in eine mobile App anstatt.

Voraussetzungen

Stellen Sie sicher, dass Sie diese installiert haben:

  • Node.js 18+ (überprüfen Sie dies mit node --version)
  • Bun Paketmanager (curl -fsSL https://bun.sh/install | bash)
  • Xcode (nur für macOS, für iOS-Entwicklung)
  • Android Studio (für Android-Entwicklung)

Schritt 1: Erstellen Sie ein neues Next.js-Projekt

Beginnen Sie mit der Erstellung eines frischen Next.js 15-Projekts:

bunx create-next-app@latest my-mobile-app

Wenn Sie dazu aufgefordert werden, wählen Sie diese Optionen:

  • TypeScript: Ja (empfohlen)
  • ESLint: Ja
  • Tailwind CSS: Ja (empfohlen für mobiles Styling)
  • src/ Verzeichnis: Ja
  • App Router: Ja (empfohlen)
  • Import-alias: Standard (@/*)

Navigiere zu deinem Projekt:

cd my-mobile-app

Schritt 2: Konfiguriere Next.js für statische Exporte

Capacitor erfordert statische HTML/JS/CSS-Dateien. Konfiguriere Next.js für statischen Export, indem du next.config.ts:

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'export',
  images: {
    unoptimized: true,
  },
  // Ensure trailing slashes for proper routing in Capacitor
  trailingSlash: true,
};

export default nextConfig;

Warum diese Einstellungen?

  • output: 'export' — Erzeugt statisches HTML anstatt eine Node.js-Server zu erfordern
  • images: { unoptimized: true } — Deaktiviert die Next.js Bildoptimierung (erfordert einen Server)
  • trailingSlash: true — Stellt sicher, dass die Routen in der nativen WebView korrekt sind

Schritt 3: Fügen Sie mobile Skripte hinzu

Aktualisieren Sie Ihr package.json mit mobilen Entwicklungs-Skripten:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "mobile": "bun run build && bunx cap sync",
    "mobile:ios": "bun run mobile && bunx cap open ios",
    "mobile:android": "bun run mobile && bunx cap open android"
  }
}

Testen Sie die Veröffentlichung:

bun run build

Sie sollten ein out Verzeichnis mit Ihren statischen Dateien sehen.

Schritt 4: Installieren Sie Capacitor 8

Installieren Sie die Capacitor-Core-Pakete:

bun add @capacitor/core
bun add -D @capacitor/cli

Installieren Sie wichtige Plugins, die meisten mobilen Apps benötigen:

bun add @capacitor/app @capacitor/keyboard @capacitor/splash-screen @capacitor/status-bar @capacitor/preferences

Was diese Plugins tun:

  • @capacitor/app — Ereignisse im App-Leben (Vordergrund/Hintergrund, tiefere Links)
  • @capacitor/keyboard — Tastaturverhalten steuern
  • @capacitor/splash-screen — Kontrolle über die native App-Startschirm
  • @capacitor/status-bar — Gestaltung des Geräte-Statusbalkens
  • @capacitor/preferences — Schlüssel-Wert-Speicherung (wie localStorage, aber native)

Schritt 5: Capacitor initialisieren

Capacitor initialisieren mit Ihren Projekt-Daten:

bunx cap init "My Mobile App" com.example.mymobileapp --web-dir out

Ersetzen Sie:

  • "My Mobile App" mit Ihrem Anwendungsbezeichner
  • com.example.mymobileapp mit Ihrer App-ID (umgekehrte Domänennotation)

Dies erstellt capacitor.config.ts Aktualisieren Sie es mit Plugin-Konfiguration:

import type { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.mymobileapp',
  appName: 'My Mobile App',
  webDir: 'out',
  plugins: {
    SplashScreen: {
      launchShowDuration: 2000,
      launchAutoHide: true,
      androidScaleType: 'CENTER_CROP',
      splashFullScreen: true,
      splashImmersive: true,
    },
    Keyboard: {
      resize: 'body',
      resizeOnFullScreen: true,
    },
    StatusBar: {
      style: 'light',
    },
  },
};

export default config;

Schritt 6: Fügen Sie Native Plattformen hinzu

Installieren Sie die Plattform-Pakete:

bun add @capacitor/ios @capacitor/android

Erstellen Sie die native Projekte:

bunx cap add ios
bunx cap add android

Dies erstellt ios und android Verzeichnisse, die die native Projekte enthalten.

Schritt 7: Bauen und Ausführen

Ihre Projekt erstellen und synchronisieren mit nativen Plattformen:

bun run mobile

In iOS Simulator öffnen:

bun run mobile:ios

Oder Android-Emulator:

bun run mobile:android

In Xcode (iOS):

  1. Wählen Sie einen Simulator aus dem Geräte-Auswahlfeld
  2. Klicken Sie auf die Play-Taste oder drücken Sie Cmd + R

In Android Studio:

  1. Warten Sie, bis Gradle fertig ist, die Synchronisierung durchzuführen
  2. Wählen Sie einen Emulator aus dem Geräte-Auswahlfeld
  3. Klicken Sie auf die Run-Taste oder drücken Sie Shift + F10

Schritt 8: Live Reload einrichten

Für eine schnellere Entwicklung Live Reload aktivieren, damit Änderungen sofort auf Ihrem Gerät erscheinen.

  1. Finden Sie Ihre lokale IP-Adresse:
# macOS
ipconfig getifaddr en0

# Windows
ipconfig
  1. Erstellen Sie eine Entwicklungskonfiguration Capacitor. Fügen Sie zu capacitor.config.ts:
import type { CapacitorConfig } from '@capacitor/cli';

const devConfig: CapacitorConfig = {
  appId: 'com.example.mymobileapp',
  appName: 'My Mobile App',
  webDir: 'out',
  server: {
    url: 'http://YOUR_IP_ADDRESS:3000',
    cleartext: true,
  },
  plugins: {
    // ... same plugin config
  },
};

const prodConfig: CapacitorConfig = {
  appId: 'com.example.mymobileapp',
  appName: 'My Mobile App',
  webDir: 'out',
  plugins: {
    // ... same plugin config
  },
};

const config = process.env.NODE_ENV === 'development' ? devConfig : prodConfig;

export default config;
  1. Starten Sie den Entwicklungs-Server und kopieren Sie die Konfiguration in die native Umgebung:
bun run dev &
NODE_ENV=development bunx cap copy
  1. Rebuild in Xcode/Android Studio

Jetzt werden Änderungen an Ihrem Next.js code auf dem Gerät mit Hot-Reload aktualisiert.

Schritt 9: Erstellen Sie Ihre erste mobile Bildschirmoberfläche

Lassen Sie uns eine einfache, mobilen-freundliche Startseite erstellen. Aktualisieren Sie src/app/page.tsx:

'use client';

import { useEffect, useState } from 'react';
import { App } from '@capacitor/app';
import { Keyboard } from '@capacitor/keyboard';

export default function Home() {
  const [appInfo, setAppInfo] = useState<{ name: string; version: string } | null>(null);

  useEffect(() => {
    // Get app info on mount
    App.getInfo().then(setAppInfo).catch(console.error);

    // Handle back button on Android
    const backHandler = App.addListener('backButton', ({ canGoBack }) => {
      if (!canGoBack) {
        App.exitApp();
      } else {
        window.history.back();
      }
    });

    // Hide keyboard when tapping outside inputs
    const keyboardHandler = Keyboard.addListener('keyboardWillShow', () => {
      document.body.classList.add('keyboard-open');
    });

    return () => {
      backHandler.then(h => h.remove());
      keyboardHandler.then(h => h.remove());
    };
  }, []);

  return (
    <main className="min-h-screen bg-linear-to-b from-blue-500 to-blue-700 flex flex-col items-center justify-center p-6 text-white">
      <h1 className="text-4xl font-bold mb-4">My Mobile App</h1>
      <p className="text-xl mb-8 text-center opacity-90">
        Built with Next.js 15 + Capacitor 8
      </p>

      {appInfo && (
        <div className="bg-white/20 rounded-lg p-4 backdrop-blur-sm">
          <p className="text-sm">
            {appInfo.name} v{appInfo.version}
          </p>
        </div>
      )}

      <div className="mt-12 space-y-4 w-full max-w-sm">
        <button className="w-full py-4 px-6 bg-white text-blue-600 rounded-xl font-semibold text-lg shadow-lg active:scale-95 transition-transform">
          Get Started
        </button>
        <button className="w-full py-4 px-6 bg-white/20 text-white rounded-xl font-semibold text-lg backdrop-blur-sm active:scale-95 transition-transform">
          Learn More
        </button>
      </div>
    </main>
  );
}

Schritt 10: Fügen Sie die Verarbeitung von sicheren Bereichen hinzu

Mobile Geräte haben Notch, Home-Indikatoren und Statusleisten. Fügen Sie die Verarbeitung von sicheren Bereichen mit Tailwind hinzu.

Aktualisieren src/app/globals.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
  --sat: env(safe-area-inset-top);
  --sar: env(safe-area-inset-right);
  --sab: env(safe-area-inset-bottom);
  --sal: env(safe-area-inset-left);
}

body {
  padding-top: var(--sat);
  padding-right: var(--sar);
  padding-bottom: var(--sab);
  padding-left: var(--sal);
}

/* Prevent text selection on mobile */
* {
  -webkit-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}

/* Allow text selection in inputs */
input, textarea {
  -webkit-user-select: auto;
  user-select: auto;
}

/* Keyboard handling */
.keyboard-open {
  --sab: 0px;
}

Projektstruktur

Ihr Projekt sollte jetzt wie folgt aussehen:

my-mobile-app/
├── android/              # Android native project
├── ios/                  # iOS native project
├── out/                  # Static build output
├── src/
│   ├── app/
│   │   ├── globals.css
│   │   ├── layout.tsx
│   │   └── page.tsx
│   └── ...
├── capacitor.config.ts   # Capacitor configuration
├── next.config.ts        # Next.js configuration
├── package.json
└── ...

Nächste Schritte

Sie haben jetzt eine funktionierende Next.js-Mobilanwendung. Hier sind die nächsten Schritte:

Wichtige Einrichtungen

  • App-Ikone: Ersetzen Sie die Standardikonen in ios/App/App/Assets.xcassets und android/app/src/main/res
  • Splash-Screen: Anpassen in native Projekten oder verwenden @capacitor/splash-screen config
  • Tiefe Links: Konfigurieren Sie die URL-Schemata für Ihre App

Hinzufügen von weiteren Funktionen

  • Kamera: bun add @capacitor/camera
  • Geolocation: bun add @capacitor/geolocation
  • Push-Benachrichtigungen: bun add @capacitor/push-notifications
  • Dateisystem: bun add @capacitor/filesystem

Benutzerinterface-Verbesserung

Überlegen Sie, hinzuzufügen Konsta UI für native aussehende iOS/Android-Komponenten:

bun add konsta

Über-der-Luft-Updates

Einrichten Sie Capgo um Updates ohne App-Store-Wiederabreitstellung zu pushen:

bunx @capgo/cli init

Fehlersuche

Der Build fehlt mit „Cannot find module“ Ausführen bun install und noch einmal versuchen.

iOS: „Kein Signierungsidentität gefunden“ Öffnen Sie Xcode, gehen Sie zu Signing & Capabilities und wählen Sie Ihr Entwicklungsteam.

Android: „SDK-Ort nicht gefunden“ Erstellen android/local.properties mit sdk.dir=/path/to/android/sdk

Änderungen erscheinen nicht auf dem Gerät Stellen Sie sicher, dass Sie bun run mobile nachdem Sie Änderungen vorgenommen haben. Für Live-Reload überprüfen Sie, ob die IP-Adresse korrekt ist und der Entwicklungs-Server läuft.

Ressourcen

Bereit, Ihre App zu verschicken? Lernen Sie, wie Capgo Ihnen helfen kann, Updates schneller zu liefern — sich für ein kostenloses Konto anmelden heute.

Live-Updates für Capacitor-Anwendungen

Wenn ein Fehler im Web-Schicht lebt, liefern Sie die Reparatur über Capgo anstatt Tage zu warten, bis die Anwendungsbewilligung genehmigt ist. Die Benutzer erhalten das Update im Hintergrund, während native Änderungen im normalen Review-Verfahren bleiben.

Jetzt loslegen

Neueste aus unserem Blog

Capgo bietet Ihnen die besten Einblicke, die Sie benötigen, um eine wirklich professionelle mobile App zu erstellen.