快速导航
教程

使用 Capacitor 8 从零开始构建一个 Next.js 移动应用

一步一步的指南,创建一个新的 Next.js 15 项目并将其转换为使用 Capacitor 8 的原生 iOS 和 Android 移动应用。适合从零开始进行移动优先开发。

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

介绍

想从头开始使用 Next.js 构建一个移动应用吗?本教程将指导您创建一个全新的 Next.js 15 项目,配置为从一开始就支持移动设备,然后将其打包为原生 iOS 和 Android 应用 Capacitor 8.

到本教程结束时,您将拥有一个可以在模拟器上运行的工作移动应用,可以继续开发并最终发布到 App Store 和 Google Play

所需时间: ~30 分钟

你将要构建的内容:

  • 一个新的 Next.js 15 项目,带有 App Router
  • 静态导出配置文件,适用于移动设备
  • Capacitor 8,带有必需的插件
  • 原生 iOS 和 Android 应用
  • 实时重新加载开发环境

已经有一个 Next.js 应用了吗? 转换您的 Next.js 应用到移动设备 查看

先决条件

确保您已安装这些:

  • Node.js 18+ (请检查) node --version)
  • Bun 包管理器(curl -fsSL https://bun.sh/install | bash)
  • Xcode (仅限macOS,用于iOS开发)
  • 安卓 Studio (用于Android开发)

步骤 1:创建一个新 Next.js 项目

首先创建一个新的 Next.js 15 项目:

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

当提示时,请选择这些选项:

  • TypeScript: 是 (推荐)
  • ESLint: 是
  • Tailwind CSS: 是 (推荐用于移动端样式)
  • src/ 目录: 是
  • 应用路由器: 是 (推荐)
  • 导入别名: 默认 (@/*)

前往您的项目:

cd my-mobile-app

第 2 步:配置 Next.js 静态导出

Capacitor 需要静态 HTML/JS/CSS 文件。通过更新 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 — 确保在原生 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/应用 —— 应用程序生命周期事件(前台/后台,深度链接)
  • @capacitor/键盘 —— 控制键盘行为
  • @capacitor/启动屏幕 —— 原生启动屏幕控制
  • @capacitor/状态栏 —— 风格设备状态栏
  • @capacitor/首选项 — 本地存储(类似localStorage,但原生)

第 5 步:初始化 Capacitor

Initialize Capacitor with your project details:

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

Replace:

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

上下文:关于 Capgo 页面。角色:UI 标签。见于:关于 .astro 页面。消息键 `about_how_step_label`(关于如何步骤标签)。

bunx cap add ios
bunx cap add android

This creates 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 完成同步
  2. 选择一个模拟器从设备下拉菜单中
  3. 点击运行按钮或按 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
  • 启动屏幕: 自定义在本机项目中或使用 @capacitor/splash-screen 配置
  • 深度链接: 为您的应用配置 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 仓库

为 Next.js 特定设置

修复 iOS 布局问题(视口、安全区域和水平溢出) overflow-x: hidden 或调整视口标签通常无法解决问题。按照以下检查顺序进行工作。

确保视口元标签正确应用

应用路由器 (app/):导出 viewport 从 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安全区域

创建一个单一的应用程序壳并在其中应用安全区域填充 — 不在多个嵌套组件中:

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看起来被裁剪或过大。

With @capgo/Tailwind-capacitor,你可以使用类似于 pt-safe pb-safe px-safe 在同一个 shell 中。

设置CapacitoriOS contentInset 到 never first

首先 capacitor.config.tsIn contentInsetMode: 'css',更倾向于使用原生边距禁用,并让CSS(或Native Navigation的)

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

混合Capacitor的自动内容内边距与CSS env(safe-area-inset-*) 混合__CAPGO_KEEP_0__的自动内容边距与CSS边距是双倍间距的常见原因。

找到真实的溢出元素

通常的罪魁祸首是使用 100vw, Tailwind w-screen, 固定像素宽度,或一个大 min-width.

In 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 with w-full 当可能时,许多水平溢出问题来自 100vw / w-screen, 重复的安全区域填充,或一个固定宽度容器 —— 不是来自视口元标签本身。

无线更新

设置 Capgo 为了不需要重新提交应用商店更新:

bunx @capgo/cli init

故障排除

无法找到模块 运行 bun install 在Capgo的市场网站上,为了让您的应用程序能够在移动设备上运行,您需要遵循以下步骤:首先,您需要在您的项目中安装Capacitor,然后您需要使用Capgo的CodePush功能来部署您的应用程序。Capgo的CodePush功能允许您在不需要重新提交应用商店更新的情况下推送更新。

并尝试再次运行。 iOS:找不到签名身份

安卓:“SDK”位置未找到 Create android/local.properties 创建 sdk.dir=/path/to/android/sdk

与 更改未在设备上显示 bun run mobile 修改完成后。为了实时重载,请确保 IP 地址正确并且开发服务器正在运行。

资源

准备好将您的应用程序交付吗?了解如何使用 Capgo 快速交付更新 — 注册免费账户 今天。

继续使用从头开始构建一个 Next.js 移动应用程序的 Capacitor 8

如果您正在使用 Build a Next.js Mobile App from Scratch with Capacitor 8 为了计划CI/CD自动化,连接它 Capgo CI/CD 为产品工作流程在Capgo CI/CD中 Capgo 原生构建 Capgo CI/CD Capgo 集成 for the product workflow in Capgo CI/CD 在 Capgo CI/CD 中的产品工作流 __CAPGO_KEEP_0__ Native Builds GitHub 行为集成 为 GitHub 的实现细节在 __CAPGO_KEEP_1__ Actions Integration 中。

通过 Capacitor 为应用程序提供实时更新

当 web-layer 的 bug 活跃时,通过 Capgo 将修复推送到应用程序,而不是等待几天的应用商店批准。用户在后台接收更新,而本机更改保持在正常的审查路径中。

最新博客

Capgo 给您创建真正专业移动应用所需的最佳见解。