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

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

Step-by-step guide to creating a new Next.js 15 project and turning it into native iOS and Android mobile apps using Capacitor 8. Perfect for starting fresh with mobile-first development.

記事のクレジット

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

ライター

ヴァレリア

レビュアー

ジョーダン

エディター

Capacitor 8を使ってNext.jsモバイルアプリケーションからゼロから

導入

Next.jsモバイルアプリケーションを作成したい このガイドでは、Next.js 15プロジェクトを作成し、モバイル用に設定し、Capacitor 8を使用してiOSおよびAndroidアプリケーションにパッケージ化する方法を説明します。 8.

__CAPGO_KEEP_0__

このチュートリアルを終了すると、シミュレータ上で実行可能なモバイルアプリケーションを開発し、続けて開発し、最終的にApp StoreおよびGoogle Playに公開することができます。 所要時間:

~30分

  • 作成するもの:
  • 新しいNext.js 15プロジェクト
  • Capacitor 8 with essential plugins
  • iOSおよびAndroid用ネイティブアプリ
  • ライブリロード開発環境

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

前提条件

次のものがインストールされていることを確認してください:

  • Node.js 18+ ( node --version)
  • Bun パッケージマネージャーで確認してください (curl -fsSL https://bun.sh/install | bash)
  • Xcode (macOS only, for iOS development)
  • 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: はい (推奨)
  • Import alias: Default (@/*)

プロジェクトに移動する:

cd my-mobile-app

ステップ 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' — 静的 HTML を生成するため、Node.js サーバーが必要なくなる
  • images: { unoptimized: true } — Next.js の画像最適化を無効にする (サーバーが必要)
  • trailingSlash: true — 本来のルーティングをnative WebViewで確実に実行する

Step 3: Mobile スクリプトを追加する

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 Step 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

@__CAPGO_KEEP_0__/app

  • @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

これにより ios 、 android コンテンツディレクトリにネイティブ プロジェクトが含まれる

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

プロジェクトをビルドし、ネイティブ プラットフォームと同期してください

bun run mobile

iOS シミュレーターで開く:

bun run mobile:ios

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

bun run mobile:android

Xcode (iOS) で:

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

Android Studio で:

  1. Gradle の Syncing が完了するのを待つ
  2. デバイス ドロップダウンからエミュレーターを選択
  3. Run ボタンをクリックまたは Shift + F10

ステップ 8: ライブ リロードを設定

開発が速くなるように、ライブ リロードを有効にして、デバイス上で即座に変更が反映されるようにする

  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モバイルアプリを持っています。ここで何をするか?

基本設定

  • アプリアイコン: デフォルトのアイコンを置き換える ios/App/App/Assets.xcassets と android/app/src/main/res
  • ページ/エリア: Capgoマーケティングウェブサイト。役割: 短いUIラベルまたはナビゲーションアイテム。見られる場所: page trust.astro。メッセージキー `and` (And)。 スプラッシュスクリーン: @capacitor/splash-screen ネイティブプロジェクトでカスタマイズするか、または
  • config デープリンク:

アプリの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

参照 Using @capgo/capacitor-native-navigation, Capacitorを使用した@capgo/capacitor-ネイティブナビゲーションCapacitorを使用した@__CAPGO_KEEP_0__/__CAPGO_KEEP_1__-トランジション tailwind-capacitor repo tailwind-__CAPGO_KEEP_0__ リポジトリ

Next.js固有の設定用

iOSレイアウトの修正 (ビューポート、セーフエリア、水平オーバーフロー) overflow-x: hidden iOSでコンテンツが切り取られた、ずれた、または水平方向にスクロールできる場合、ビューポートタグを追加または調整するだけでは通常解決されません。次の順序でこれらのチェックを実行してください。

ビューポートメタタグが正しく適用されていることを確認する

Appルーター (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.tsxではなく _document.tsx.

iOS セーフエリアを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を使用して、同じパディングを表現できます。 pt-safe pb-safe px-safe でiOS

Set Capacitor iOS contentInset に never 最初

In capacitor.config.ts, contentInsetMode: 'css'原生インセットを有効にし、CSS (またはNative Navigationの)

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-*) __CAPGO_KEEP_0__の自動コンテンツインセットとCSSのパディングを組み合わせると、通常はダブルスペースが発生します。

実際にオーバーフローしている要素を探します。

通常の原因は、 100vw、 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

トラブルシューティング

エラーが発生し、「モジュールが見つかりません」と表示される場合 を実行 bun install そして再度試してみてください。

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

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

デバイスに表示されない変更 変更を実行した後、確実に bun run mobile Live reload の場合、IP アドレスが正しいかどうかと、開発サーバーが実行中であることを確認してください。

Resources

アプリを配信する準備ができましたか? Capgo を使用して、更新を迅速に配信する方法を学びましょう — 無料アカウントに登録する 今日。

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

Capacitorを使用している場合 Build a Next.js Mobile App from Scratch with Capacitor 8 CI/CDの自動化を計画するには、CI/CDの自動化に接続する Capgo CI/CD Capgo CI/CDの製品ワークフロー Capgo Native Builds Capgo Native Builds Capgo Integrations Capgo Integrations __CAPGO_KEEP_0__ Integrations CI/CD統合 GitHub CI/CD統合 GitHub Actions統合

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

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

マーティンから人間のサポートを受けます。

今すぐ始めましょう。

最新のブログ記事

Capgo は、プロフェッショナルなモバイル アプリを作成するために必要な最良の洞察を提供します。