はじめに
Next.js でモバイルアプリをゼロから作りたいですか?このガイドでは、最初からモバイル向けに設定された新しい Next.js 15 プロジェクトを作成し、iOS と Android のネイティブアプリとしてパッケージ化するまでを、以下を使って解説します。 Capacitor 8.
このチュートリアルを終える頃には、シミュレーターで動くモバイルアプリが完成し、そのまま開発を続けて最終的に App Store と Google Play に公開できます。
所要時間: 約30分
作成するもの:
- App Routerを使用した新しいNext.js 15プロジェクト
- モバイル向けの静的エクスポート設定
- Capacitor 8(必須プラグイン付き)
- iOSとAndroidのネイティブアプリ
- Live reloadの開発環境
既存のNext.jsアプリがありますか?こちらをチェック: Next.jsアプリをモバイルアプリに変換 こちらを読んでください。
前提条件
以下のツールがインストールされていることを確認してください:
- Node.js 18以上 (確認:
node --version) - Bun パッケージマネージャー(
curl -fsSL https://bun.sh/install | bash) - iOSプロファイリング (macOSのみ、iOS開発用)
- デバッグ (Android開発用)
ステップ1:新しい Next.js プロジェクトの作成
まずは、新しい Next.js 15 プロジェクトを作成します:
bunx create-next-app@latest my-mobile-app
プロンプトが表示されたら、以下のオプションを選択してください:
- TypeScript: 使用する (推奨)
- ESLint: はい
- Tailwind CSS: 使用する (モバイルのスタイリングに推奨)
src/採用されています: はい- App Router: 使用する (推奨)
- Import alias: デフォルト (
@/*)
プロジェクトへ移動:
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'— Node.js サーバーを必要とせず、静的な HTML を生成するためimages: { unoptimized: true }— Next.js Image Optimization を無効化するため(サーバーが必要なため)trailingSlash: true— ネイティブ WebView で適切なルーティングを確保するため
ステップ 3: モバイルスクリプトを追加
以下のファイルを更新して、 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 — キーバリューストレージ(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 Simulatorで開く:
bun run mobile:ios
またはAndroid Emulator:
bun run mobile:android
Xcode (iOS) で:
- デバイスのドロップダウンからシミュレータを選択
- 再生ボタンをクリックするか、以下を押下:
Cmd + R
Android Studio で:
- Gradleの同期完了を待機します
- デバイスのドロップダウンからエミュレータを選択します
- Runボタンをクリックするか、以下を押します
Shift + F10
ステップ 8: Live Reload の設定
開発を高速化するには、live reloadを有効にすると変更が即座にデバイスに反映されます。
- ローカルIPアドレスを確認してください:
# macOS
ipconfig getifaddr en0
# Windows
ipconfig
- 開発用の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;
- 開発サーバーを起動し、設定をネイティブにコピーします:
bun run dev &
NODE_ENV=development bunx cap copy
- 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 - スプラッシュ画面: ネイティブプロジェクトでカスタマイズするか、次を使う
@capacitor/splash-screen設定 - ディープリンク: アプリのURLスキームを設定する
さらに機能を追加
- カメラ:
bun add @capacitor/camera - 位置情報:
bun add @capacitor/geolocation - プッシュ通知:
bun add @capacitor/push-notifications - ファイルシステム:
bun add @capacitor/filesystem
ネイティブUIとトランジション
ネイティブなモバイル体験を実現するために、Konsta UIの代わりに Capgo プラグインを使用しましょう:
- @capgo/capacitor-native-navigation — Liquid Glass タブバーとネイティブのナビゲーションバー
- @capgo/capacitor-transitions — ネイティブ感のあるページ遷移
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 リポジトリ Next.js 専用のセットアップ用
iOSのレイアウト問題を修正(ビューポート、セーフエリア、横方向のオーバーフロー)
iOSでコンテンツが切れて見えたり、ずれて見えたり、横スクロールが発生したりする場合は、さらに追加するだけでも、 overflow-x: hidden viewportタグを調整するだけでも通常は解決しません。以下のチェックを順番に確認してください。
viewport メタタグが正しく適用されているか確認する
App Router (app/): export viewport と app/layout.tsx:
import type { Viewport } from 'next';
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
viewportFit: 'cover',
};
Pages Router (pages/): viewportのmetaタグはここに配置します 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ヘッダー、モーダル、レイアウトラッパーで safe-area のパディングが重複すると、UI が欠けたり、逆に大きすぎたりすることがよくあります。
を使用すると、 @capgo/tailwind-capacitor同じパディングを次のようなユーティリティで表現できます: pt-safe pb-safe px-safe その単一のシェル上で。
Capacitor iOS を設定 contentInset まで never 最初に
では capacitor.config.ts、native inset を無効にすることを推奨し、CSS(または Native Navigation のもの contentInsetMode: 'css')に safe area を任せる:
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'my-app',
webDir: 'out',
ios: {
contentInset: 'never',
},
};
Capacitor の自動コンテンツ inset と CSS を混在させると env(safe-area-inset-*) paddingが原因で、余白が二重に見えることがよくあります。
実際にオーバーフローしている要素を特定する
主な原因は、以下の要素を使用している場合です: 100vwTailwind CSS、 w-screen固定ピクセル幅、または大きな min-width.
Safari Web Inspectorで以下を実行してください:
[...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、重複したセーフエリアのパディング、または固定幅のコンテナに起因し、viewportのmetaタグ自体が原因ではありません。
Over-the-Air アップデート
セットアップ Capgo App Storeへの再申請なしでアップデートを配信するには:
bunx @capgo/cli init
トラブルシューティング
ビルドエラー: “Cannot find module”
実行 bun install もう一度お試しください。
iOS: 「No signing identity found」 Xcodeを開き、Signing & Capabilitiesで開発チームを選択してください。
Android: “SDK の場所が見つかりません”
作成します android/local.properties を使用して sdk.dir=/path/to/android/sdk
デバイスに変更が反映されない
変更を加えた後は、必ず以下を実行してください: bun run mobile ライブリロードを使用する場合は、IPアドレスが正しいことと、開発サーバーが起動していることを確認してください。
リソース
- Capacitor 8 ドキュメント
- Next.js 15 ドキュメント
- Capgo - Live Updates
- @capgo/capacitor-native-navigation
- @capgo/capacitor-transitions
- @capgo/tailwind-capacitor
アプリをリリースする準備はできましたか?Capgo を使って、より素早くアップデートを配信する方法を学びましょう — 無料アカウントに登録する を今すぐ作成してください。
Capacitor で Next.js モバイルアプリをゼロから構築する(ステップ8)の続きから
使用している場合 Capacitor 8 を使って Next.js モバイルアプリをゼロから作る CI/CD自動化を計画するには、次と連携してください Capgo での CI/CD 設定 Capgo CI/CDでのプロダクトワークフローについては、 Capgo Native Build Capgo Native Buildsでのプロダクトワークフローについては、 Capgo インテグレーション Capgo インテグレーションでのプロダクトワークフロー向けに、 CI/CD 連携 CI/CD Integrationの実装詳細については、 GitHub Actions 連携 GitHub Actions Integrationの実装詳細については。