简介
想从零开始用 Next.js 构建移动应用吗?本指南将带你创建一个从第一天起就为移动端配置好的全新 Next.js 15 项目,然后使用 Capacitor 8.
学完本教程,你将拥有一个可在模拟器上运行的移动应用,可以继续开发,并最终发布到 App Store 和 Google Play。
预计耗时: ~30 分钟
你将构建:
- 基于 App Router 的全新 Next.js 15 项目
- 针对移动端的静态导出配置
- 带必备插件的 Capacitor 8
- iOS 和 Android 原生 App
- Live reload 开发环境搭建
已有 Next.js 应用?请查看 将您的 Next.js 应用转换为移动应用 请改用这种方式。
前提条件
请确保已安装以下内容:
- Node.js 18+ (用
node --version) - Bun 包管理器(
curl -fsSL https://bun.sh/install | bash) - Xcode 的 Mac (仅限 macOS,用于 iOS 开发)
- Android Studio 中的错误日志 (用于 Android 开发)
第一步:创建一个新的 Next.js 项目
首先创建一个全新的 Next.js 15 项目:
bunx create-next-app@latest my-mobile-app
出现提示时,选择以下选项:
- TypeScript: 是 (推荐)
- ESLint: 是
- Tailwind CSS: 是 (推荐用于移动端样式)
src/目录: 是- App Router: 是 (推荐)
- 导入别名: 默认 (
@/*)
进入你的项目目录:
cd my-mobile-app
第二步:配置 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 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 模拟器中打开:
bun run mobile:ios
或 Android 模拟器:
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配置 - Deep Links: 为你的 App 配置 URL schemes
添加更多功能
- Camera:
bun add @capacitor/camera - Geolocation:
bun add @capacitor/geolocation - Push Notifications:
bun add @capacitor/push-notifications - File System:
bun add @capacitor/filesystem
原生 UI 与转场效果
使用 Capgo 插件代替 Konsta UI,获得原生移动端体验:
- @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 meta 标签已正确应用
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 安全区域
创建一个统一的 app shell,并在其中应用 safe area 内边距,而不是在多个嵌套组件中:
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。在 header、modal 和 layout wrapper 中重复设置 safe-area padding 往往会让 UI 看起来被裁剪或过大。
使用 @capgo/tailwind-capacitor,你可以使用如下 utility 类来实现相同的 padding pt-safe pb-safe px-safe 在这个单一 shell 上。
设置 Capacitor iOS contentInset 改为 never 首先
在 capacitor.config.ts,建议禁用 native inset,让 CSS(或 Native Navigation 的 contentInsetMode: 'css')来管理安全区域:
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'my-app',
webDir: 'out',
ios: {
contentInset: 'never',
},
};
将 Capacitor 的自动 content inset 与 CSS env(safe-area-inset-*) padding 混合使用,是导致间距翻倍的常见原因。
找到真正溢出的元素
常见原因是某个元素使用了 100vw,Tailwind 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重复的 safe-area 内边距或固定宽度容器,而不是 viewport meta 标签本身。
OTA 更新
设置 Capgo 无需重新提交 App Store 即可推送更新:
bunx @capgo/cli init
故障排除
构建失败,提示 “Cannot find module”
运行 bun install 然后重试。
iOS: “No signing identity found” 打开 Xcode,进入 Signing & Capabilities,然后选择你的开发团队。
Android: “SDK location not found”
创建 android/local.properties 配合 sdk.dir=/path/to/android/sdk
设备上未显示更改
请确保已运行 bun run mobile (请在更改后执行)。如需使用 live reload,请确认 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 集成的实现细节,以及 GitHub Actions 集成 有关 GitHub Actions 集成的实现细节。