メインコンテンツにジャンプ
チュートリアル

Capacitor 8を使ってNext.jsモバイルアプリを作成する

Capacitor 8を使用して、Next.js 15プロジェクトを作成し、iOSおよびAndroidモバイルアプリに変換するステップバイステップガイド。モバイルファースト開発を始めるのにぴったりです。

マーティン・ドナディュー

マーティン・ドナディュー

コンテンツマーケター

Capacitor 8を使ってNext.jsモバイルアプリを作成する

導入

Want to build a mobile app with Next.js from the ground up? Capacitor 8.

__CAPGO_KEEP_0__

このチュートリアルを終了すると、シミュレータ上で動作するワークイングモバイルアプリを持つことになります。これを開発し、最終的にApp StoreとGoogle Playに公開することができます。 所要時間:

~30分

  • 作成するもの:
  • 新しいNext.js 15プロジェクトとApp Router
  • Capacitor 8 with essential plugins
  • __CAPGO_KEEP_0__ 8に必要なプラグイン
  • ネイティブiOSとAndroidアプリ

既にNext.jsアプリを持っていますか? こちらを確認してください。 Next.jsアプリをモバイルに変換する それ以外。

前提条件

以下をインストールしておいてください。

  • Node.js 18+ ( node --version)
  • Bun パッケージマネージャー (curl -fsSL https://bun.sh/install | bash)
  • Xcode (macOSのみ、iOS開発用)
  • Android Studio (for Android development)

Step 1: Next.js プロジェクトを作成する

はじめに、最新の Next.js 15 プロジェクトを作成します。

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

入力を求められたら、次のオプションを選択してください。

  • TypeScript: はい (推奨)
  • ESLint: はい
  • Tailwind CSS: はい (モバイルスタイリングの推奨)
  • src/ ディレクトリ: はい
  • App Router: Yes (recommended)
  • Import alias: Default (@/*)

Navigate to your project:

cd my-mobile-app

Step 2: Next.jsを静的エクスポート用に設定する

Capacitorは静的HTML/JS/CSSファイルが必要です。Next.jsを静的エクスポート用に設定するには、 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;

これらの設定の理由は?

  • output: 'export' — Node.jsサーバーが必要なく静的HTMLを生成する
  • images: { unoptimized: true } — Next.jsの画像最適化を無効にする (サーバーが必要)
  • trailingSlash: true — ネイティブのWebViewで適切なルーティングを確保する

Step 3: モバイルスクリプトを追加する

Update your package.json モバイル開発スクリプトとともに

{
  "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"
  }
}

テストビルド:

bun run build

ここで、 out 静的ファイルが入ったディレクトリが見つかります。

ステップ4: Capacitor 8をインストールする

Capacitorのコアパッケージをインストールする

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

モバイルアプリに必要な基本的なプラグインをインストールする

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

これらのプラグインは何を実行する?

  • @capacitor/app — フォアグラウンド/バックグラウンドのライフサイクルイベント、ディープリンク
  • @capacitor/keyboard — キーボードの動作を制御する
  • @capacitor/splash-screen — 本機のスプラッシュ画面の制御
  • @capacitor/status-bar — デバイスのステータスバーのスタイル
  • @capacitor/preferences — 値を格納するためのキー・バリューストレージ(ローカルストレージと同様のもの)

Step 5: Capacitorを初期化する

Capacitorをプロジェクトの詳細と初期化する:

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

置き換え:

  • "My Mobile App" アプリの表示名
  • com.example.mymobileapp アプリID(逆ドメイン表記)

これは作成します。 capacitor.config.ts__CAPGO_KEEP_0__を更新してください:プラグインの構成

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;

ステップ 6:ネイティブプラットフォームを追加する

プラットフォームパッケージをインストールする:

bun add @capacitor/ios @capacitor/android

ネイティブプロジェクトを生成する:

bunx cap add ios
bunx cap add android

これは作成します。 iosandroid ネイティブプロジェクトを含むディレクトリ。

ステップ 7:ビルドと実行

プロジェクトをビルドし、ネイティブプラットフォームと同期する:

bun run mobile

iOS シミュレータで開く:

bun run mobile:ios

またはAndroid エミュレータで開く:

bun run mobile:android

In Xcode (iOS):

  1. デバイスドロップダウンからシミュレータを選択してください
  2. Playボタンをクリックまたは Cmd + R

In Android Studio:

  1. Gradleの同期を待ってください
  2. デバイスドロップダウンからエミュレータを選択してください
  3. Runボタンをクリックまたは Shift + F10

Step 8: Live Reloadを設定する

開発が速くなるように、ライブリロードを有効にしてください。変更は即座にデバイスに表示されます。

  1. ローカルIPアドレスを探してください:
# macOS
ipconfig getifaddr en0

# Windows
ipconfig
  1. 開発用Capacitor設定を作成してください。に追加してください 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. 開発サーバーを起動し、設定をネイティブにコピーしてください
bun run dev &
NODE_ENV=development bunx cap copy
  1. Xcode/Android Studioで再構築

あなたのNext.js codeの編集は、デバイスで即時反映されます。

ステップ 9: 最初のモバイル画面を作成する

モバイルフレンドリーなホーム画面を作成しましょう。更新 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>
  );
}

ステップ 10: セーフエリアハンドリングを追加する

モバイルデバイスにはノッチ、ホームインジケータ、ステータスバーがあります。Tailwindでセーフエリアハンドリングを追加してください。

更新 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;
}

プロジェクト構造

あなたのプロジェクトは次のようになります。

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
└── ...

次のステップ

あなたは機能するNext.jsモバイルアプリを持っています。ここで何をするかをご紹介します。

基本設定

  • App Icons: デフォルトのアイコンを置き換える ios/App/App/Assets.xcassetsandroid/app/src/main/res
  • Splash Screen: ネイティブプロジェクトでカスタマイズするか、configを使用して @capacitor/splash-screen config
  • Deep Links: アプリのURLスキームを設定する

機能を追加する

  • カメラ: bun add @capacitor/camera
  • 位置情報: bun add @capacitor/geolocation
  • プッシュ通知: bun add @capacitor/push-notifications
  • ファイル システム: bun add @capacitor/filesystem

ネイティブ UI とトランジション

Capgo プラグインを使用して、Konsta UI の代わりにネイティブモバイルのフィールを実現します:

bun add @capgo/capacitor-native-navigation @capgo/capacitor-transitions
bunx cap sync

Tailwind の安全エリアを追加するには @capgo/tailwind-capacitor:

bun add -D tailwind-capacitor

参照 使用中: @capgo/capacitor-native-navigation, 使用中: @capgo/capacitor-transitions、そして tailwind-capacitor リポジトリ Capgo用のNext.js固有の設定

iOSレイアウトの問題を修正 (ビューポート、セーフエリア、水平オーバーフロー)

iOSでコンテンツが切り取られた、ずれた、または水平方向にスクロールできる場合、ビューポートタグを追加または調整するだけでは問題が解決しないことがあります。順序に従ってこれらのチェックを実行してください。 overflow-x: hidden ビューポートメタタグが正しく適用されていることを確認する

App Router

): export (app/from viewport Pages Router app/layout.tsx:

import type { Viewport } from 'next';

export const viewport: Viewport = {
  width: 'device-width',
  initialScale: 1,
  viewportFit: 'cover',
};

): ビューポートメタタグを (pages/__CAPGO_KEEP_0__ pages/_app.tsx, ない _document.tsx.

iOS セーフエリアを 1 つのルートラッパーからのみ取り扱う

1 つのアプリシェルを作成し、その中にセーフエリアのパディングを適用する — 複数のネストされたコンポーネントに適用するのではなく:

html,
body,
#__next {
  width: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

* {
  box-sizing: border-box;
}

.app-shell {
  min-height: 100dvh;
  width: 100%;
  padding-top: env(safe-area-inset-top);
  padding-right: env(safe-area-inset-right);
  padding-bottom: env(safe-area-inset-bottom);
  padding-left: env(safe-area-inset-left);
}

すべてのページコンテンツを .app-shell. ヘッダー、モーダル、レイアウトラッパーなどでセーフエリアのパディングを複数回適用すると、UI がカットされたり大きすぎるように見えることがある。

そして @capgo/tailwind-capacitor, 1 つのシェルにパディングを適用することで、同じパディングを表現することができる。 pt-safe pb-safe px-safe セーフエリアのパディングを iOS に

Set Capacitor iOS contentInset 最初に never __CAPGO_KEEP_0__

In capacitor.config.tsnativeのインセットを無効にして、CSS(またはNative Navigationの)が安全エリアを制御することをお勧めします。 contentInsetMode: 'css'__CAPGO_KEEP_0__の自動コンテンツインセットとCSSのパディングを組み合わせると、一般的なダブルスペースの原因となります。

const config: CapacitorConfig = {
  appId: 'com.example.myapp',
  appName: 'my-app',
  webDir: 'out',
  ios: {
    contentInset: 'never',
  },
};

Mixing Capacitor’s automatic content inset with CSS env(safe-area-inset-*) 通常の原因は、

Tailwind

固定ピクセル幅、または大きい 100vwSafari Web Inspectorで実行します: w-screenTailwindの場合、 min-width.

に置き換えます.

[...document.querySelectorAll('*')]
  .filter(el => el.scrollWidth > document.documentElement.clientWidth)
  .map(el => ({
    el,
    tag: el.tagName,
    class: el.className,
    scrollWidth: el.scrollWidth,
    clientWidth: document.documentElement.clientWidth,
  }));

with w-screen に置き換えます. w-full 可能であれば。多くの水平オーバーフロー問題は、安全エリアの重複パディングや固定幅のコンテナから来ています — 画面のメタタグ自体ではありません。 100vw / w-screenオーバー・ザ・エア更新

設定

__CAPGO_KEEP_0__ Capgo トラブルシューティング

bunx @capgo/cli init

ビルドが「モジュールが見つかりません」というエラーで失敗します

実行 再度試してください。 bun install iOS: 「署名のアイデンティティが見つかりません」

Xcodeを開き、Signing &amp; Capabilitiesに移動し、開発チームを選択してください。 Over-the-Air Updates

Android: “SDK の場所が見つかりません” 作成 android/local.propertiessdk.dir=/path/to/android/sdk

デバイスに表示されない変更 変更が表示されない場合は、変更を加えた後、再度実行してください。ライブリロードの場合、IPアドレスが正しく設定されていることを確認し、開発サーバーが実行中であることを確認してください。 bun run mobile リソース

__CAPGO_KEEP_0__ 8 ドキュメント

Capgoでアプリを迅速に更新できるように支援する方法を学びましょう 無料アカウントに登録する 今日

Capacitor 8を使用して、Next.jsモバイルアプリをゼロから構築する

__CAPGO_KEEP_0__を使用している場合 Capacitor 8を使用して、Next.jsモバイルアプリをゼロから構築する __CAPGO_KEEP_0__ CI/CDと接続する Capgo CI/CDの製品ワークフロー Capgo Native Buildsの製品ワークフロー Capgo Native Builds Capgo CI/CD Capgo アサイスバート for the product workflow in Capgo Integrations, パティショナを不機导です パティショナにを不機导です GitHub Actions Integration for the implementation detail in GitHub Actions Integration.

Capacitor アプリのリアルタイム更新

ウェブ層のバグが生じた場合、Capgo を使用して修正を配信し、数日間待つ必要のないアプリストアの承認を待つのではなく。ユーザーはバックグラウンドで更新を受け取り、ネイティブの変更は通常のレビュー パスで残ります。

始めましょう

ブログ

Capgo を使用すると、プロフェッショナルなモバイル アプリを作成するために必要な最良の洞察を得ることができます。