跳过主要内容
教程

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

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

马丁·多纳迪厄

马丁·多纳迪厄

内容营销

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

介绍

想从头开始构建一个使用 Next.js 的移动应用吗?本指南将指导您创建一个从一开始就针对移动设备配置的全新的 Next.js 15 项目,然后使用 __CAPGO_KEEP_0__ 将其打包为原生 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+ (使用 node --version)
  • Bun 包管理器(curl -fsSL https://bun.sh/install | bash)
  • Xcode (macOS only, for iOS development)
  • 安全工关学习 (for Android development)

项目 1: 初开一个新当事一.js的工关

开始一个新当事一.js 15的工关:

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

很给为一个请完成的项目。

  • 请为一个请完成的项目。 为一个请完成的项目。
  • 当前为一个请完成的项目。 是一个请完成的项目。
  • 为一个请完成的项目。 是 (推荐用于移动样式)
  • src/ __CAPGO_KEEP_0__ 目录:
  • App Router: 是 (推荐)
  • 导入别名: 默认 (@/*)

导航到您的项目:

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 — 确保在原生 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

这创建了 iosandroid 包含本机项目的目录。

步骤 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.xcassetsandroid/app/src/main/res
  • 启动屏幕: 自定义在原生项目中或使用 @capacitor/splash-screen config
  • 深度链接: 配置 URL 方案以便您的应用

添加更多功能

  • 摄像头: bun add @capacitor/camera
  • 地理位置: bun add @capacitor/geolocation
  • 推送通知: bun add @capacitor/push-notifications
  • 文件系统: bun add @capacitor/filesystem

UI 增强

考虑添加 Konsta UI 为原生 iOS/Android 组件:

bun add konsta

无线更新

设置 Capgo 无需重新发布应用商店以推送更新:

bunx @capgo/cli init

故障排除

无法找到模块: 运行 bun install 并再试一次。

iOS:无法找到签名身份 打开 Xcode,转到 Signing & Capabilities,选择您的开发团队。

Android:SDK位置未找到 创建 android/local.propertiessdk.dir=/path/to/android/sdk

设备上未显示的更改 确保您已运行 bun run mobile 在进行更改后。对于实时重载,请验证 IP 地址是否正确并且开发服务器正在运行。

资源

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

实时更新 Capacitor 应用

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

立即开始

最新博客文章

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