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

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

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

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

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

コンテンツマーケター

Build a Next.js Mobile App from Scratch with Capacitor 8

導入

Next.jsからモバイルアプリケーションを作成したい場合は、このガイドをご覧ください。このガイドでは、モバイル向けに設定されたNext.js 15プロジェクトを作成し、Native iOSおよびAndroidアプリとしてパッケージ化する方法を説明します。 Capacitor 8.

このチュートリアルを終了すると、シミュレータ上で動作するワーキングモバイルアプリケーションを手に入れることができます。このアプリケーションは、開発を続け、最終的にApp StoreおよびGoogle Playに公開することができます。

必要な時間 ~30分

作成するもの

  • App Routerを使用したNext.js 15プロジェクト
  • モバイル用の静的エクスポート設定
  • Capacitor 8 に必要なプラグイン
  • ネイティブiOSおよびAndroidアプリ
  • ライブリロード開発環境

すでにNext.jsアプリを持っていますか? Next.jsアプリをモバイルに変換する の代わりに。

前提条件

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

  • Node.js 18+ (__CAPGO_KEEP_0__ で確認してください node --version)
  • Bun パッケージマネージャー (curl -fsSL https://bun.sh/install | bash)
  • Xcode (macOSのみ、iOS開発用)
  • Android Studio (Android開発用)

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

新しいNext.js 15プロジェクトを作成する:

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

入力されたときに、次のオプションを選択してください:

  • TypeScript: はい (推奨)
  • ESLint: はい
  • Tailwind CSS: Yes (recommended for mobile styling)
  • src/ directory: Yes
  • 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で適切なルーティングを確保します

ステップ 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: __CAPGO_KEEP_0__ 8 をインストールする

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

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 — キー値の保存 (localStorageと同様のネイティブの保存)

ステップ 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を更新してください:プラグインの設定

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 ネイティブプロジェクトのディレクトリが作成されます。

Step 7: Build and Run

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

bun run mobile

iOS シミュレータで開く:

bun run mobile:ios

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

bun run mobile:android

Xcode (iOS) で:

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

Android Studio で:

  1. Gradle の同期が完了するのを待つ
  2. デバイス ドロップダウンからエミュレータを選択
  3. 実行ボタンをクリックまたは 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;
}

Project Structure

__CAPGO_KEEP_0__

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

次のステップ

__CAPGO_KEEP_1__

基本設定

  • アプリアイコン: __CAPGO_KEEP_2__ ios/App/App/Assets.xcassets デフォルトのアイコンを置き換える android/app/src/main/res
  • スプラッシュスクリーン: @capacitor/splash-screen __CAPGO_KEEP_3__
  • ネイティブプロジェクトでカスタマイズするか、 config

機能を追加

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

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

Liquid Glassタブバーとネイティブナビゲーションバーを使用することで、Capgo プラグインを使用してKonsta UIの代わりにネイティブモバイルのフィールを実現できます。

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

@__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-native-navigation @capgo/tailwind-capacitor:

bun add -D tailwind-capacitor

確認 Capgoを使用した@capgo/capacitor-native-navigation, Capgoを使用した@capgo/capacitor-transitions、そして tailwind-capacitor Next.js用の設定のためにtailwind-__CAPGO_KEEP_0__リポジトリ

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

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

App Router

App Router (app/export viewport from app/layout.tsx:

import type { Viewport } from 'next';

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

ページルーター (pages/を追加 pages/_app.tsxiOS セーフエリアを 1 つのルートラッパーからのみ取り扱う _document.tsx.

アプリシェルを 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 の @capgo/tailwind-capacitorを使用すると、パディングをユーティリティとして表現できます。 pt-safe pb-safe px-safe その単一のシェル上に。

Set Capacitor iOS contentInsetnever 最初

In capacitor.config.ts, 自然のインセットを無効にして、CSS (またはネイティブナビゲーションの contentInsetMode: 'css') が安全なエリアを所有するようにします。

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

Capacitor の自動コンテンツインセットと CSS のパディングを組み合わせることは、ダブルスペースの一般的な原因です。 env(safe-area-inset-*) 実際にオーバーフローしている要素を探します。

通常の原因は、

, Tailwind を使用する要素です。 100vwMixing __CAPGO_KEEP_0__’s automatic content inset with CSS padding is a common cause of double spacing. w-screen、ピクセル幅が固定されている場合、または大きい min-width.

Safari Web インスペクターで実行:

[...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,
  }));

Tailwind を使用すると、 w-screen に置き換える w-full 可能な場合。多くの水平方向のオーバーフロー問題は、 100vw / w-screen安全なエリアの重複したパディング、またはピクセル幅が固定されているコンテナ — ではなく、ビューポート メタタグ自体から

オーバー・ザ・エア更新

設定 Capgo アプリストアの再提出を必要とせずに更新をプッシュする:

bunx @capgo/cli init

トラブルシューティング

ビルドが「モジュールを検索できません」というエラーで失敗します Run bun install と再試行してください。

iOS: “署名のIDENTITYが見つかりません” Xcodeを開き、Signing &amp; Capabilitiesに移動し、開発チームを選択してください。

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

デバイスに表示されない変更 変更が表示されない場合は、変更を実行した後、以下の手順を実行してください。ライブリロードの場合、IPアドレスが正しいかどうか、開発サーバーが実行中かどうかを確認してください。 bun run mobile リソース

__CAPGO_KEEP_0__ 8 ドキュメント

Capgo でアプリを迅速に更新して配信する方法を学びましょう — 無料アカウントに登録する 今日。

Build a Next.js Mobile App from Scratch with Capacitor 8

__CAPGO_KEEP_0__ を使用している場合 Build a Next.js Mobile App from Scratch with Capacitor 8 CI/CD オートメーションを計画する場合、__CAPGO_KEEP_0__ に接続する Capgo CI/CD Capgo CI/CDの製品ワークフローについて Capgo Native Builds Capgo Native Buildsの製品ワークフローについて Capgo Integrations Capgo Integrationsの製品ワークフローについて CI/CD Integration CI/CD Integrationの実装詳細について GitHub Actions Integration GitHub Actions Integrationの実装詳細について

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

Capgo アプリのバグが生じた場合、修正を Capgo を通じて配信するのではなく、数日間待ってアプリストアの承認を待つのではなく、ユーザーはバックグラウンドで更新を受け取り、ネイティブの変更は通常のレビュー経路を通じて

今すぐ始めましょう

最新のブログ記事

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