跳转至正文
教程

使用 Capacitor 8 从零构建 Nuxt 移动应用

手把手教你如何创建一个全新的 Nuxt 4 项目,并使用 Capacitor 将其转化为 iOS 和 Android 原生移动应用。非常适合开启以移动端优先的 Vue 开发之旅。

使用 Capacitor 8 从零构建 Nuxt 移动应用

简介

想从零开始使用 Nuxt 构建移动应用吗?本指南将带你从第一天起就配置好全新的 Nuxt 4 移动端项目,并使用以下工具将其打包为 iOS 和 Android 原生应用: Capacitor 8.

完成本教程后,你将拥有一个可在模拟器上运行的移动应用,你可以继续进行开发,并最终将其发布到 App Store 和 Google Play。

预计耗时: ~30 分钟

你将构建:

  • 采用最新目录结构的新 Nuxt 4 项目
  • 针对移动端的静态生成配置
  • 带必备插件的 Capacitor 8
  • iOS 和 Android 原生 App
  • Live reload 开发环境搭建

已有 Nuxt 应用?请查看 将你的 Nuxt 应用转为移动端 请改用这种方式。

前提条件

请确保已安装以下内容:

  • Node.js 18+ (用 node --version)
  • Bun 包管理器(curl -fsSL https://bun.sh/install | bash)
  • Xcode 的 Mac (仅限 macOS,用于 iOS 开发)
  • Android Studio 中的错误日志 (用于 Android 开发)

第 1 步:创建新的 Nuxt 4 项目

首先创建一个全新的 Nuxt 4 项目:

bunx nuxi@latest init my-mobile-app
cd my-mobile-app
bun install

Nuxt 4 目录结构

Nuxt 4 使用了全新的目录结构,其中 app code 位于 app/ 目录中:

my-mobile-app/
  app/
    assets/
    components/
    composables/
    layouts/
    middleware/
    pages/
    plugins/
    utils/
    app.vue
  public/
  server/
  nuxt.config.ts
  package.json

这种结构实现了应用与服务端 code 更好的分离。

步骤 2:配置 Nuxt 进行静态生成

Capacitor 需要静态的 HTML/JS/CSS 文件。请配置 Nuxt 以进行静态生成, nuxt.config.ts:

export default defineNuxtConfig({
  compatibilityDate: '2025-01-15',
  devtools: { enabled: true },

  // Enable static generation
  ssr: true,
  nitro: {
    preset: 'static',
  },
});

步骤 3:添加移动端脚本

更新您的 package.json 并添加移动端开发脚本:

{
  "scripts": {
    "dev": "nuxt dev",
    "build": "nuxt build",
    "generate": "nuxt generate",
    "preview": "nuxt preview",
    "mobile": "bun run generate && bunx cap sync",
    "mobile:ios": "bun run mobile && bunx cap open ios",
    "mobile:android": "bun run mobile && bunx cap open android"
  }
}

测试静态生成:

bun run generate

你应该能看到一个 .output/public 包含静态文件的目录。

步骤 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 .output/public

替换为:

  • "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: '.output/public',
  plugins: {
    SplashScreen: {
      launchShowDuration: 2000,
      launchAutoHide: true,
      androidScaleType: 'CENTER_CROP',
      splashFullScreen: true,
      splashImmersive: true,
    },
    Keyboard: {
      resize: 'body',
      resizeOnFullScreen: true,
    },
    StatusBar: {
      style: 'dark',
    },
  },
};

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 同步完成
  2. 从设备下拉菜单中选择一个模拟器
  3. 点击 Run 按钮或按 Shift + F10

第 8 步:设置 Live Reload

为了加快开发速度,请启用 live reload,让改动即时显示在设备上。

  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: '.output/public',
  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: '.output/public',
  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 中重新构建

现在,你在 Nuxt code 中的修改将在设备上实现热重载。

第 9 步:创建你的第一个移动端页面

让我们创建一个移动端友好的主屏幕。更新 app/app.vue:

<template>
  <NuxtPage />
</template>

创建 app/pages/index.vue:

<template>
  <main
    class="min-h-screen bg-linear-to-b from-green-500 to-green-700 flex flex-col items-center justify-center p-6 text-white"
  >
    <h1 class="text-4xl font-bold mb-4">My Mobile App</h1>
    <p class="text-xl mb-8 text-center opacity-90">
      Built with Nuxt 4 + Capacitor 8
    </p>

    <div v-if="appInfo" class="bg-white/20 rounded-lg p-4 backdrop-blur-sm mb-8">
      <p class="text-sm">
        {{ appInfo.name }} v{{ appInfo.version }}
      </p>
    </div>

    <div class="space-y-4 w-full max-w-sm">
      <button
        class="w-full py-4 px-6 bg-white text-green-600 rounded-xl font-semibold text-lg shadow-lg active:scale-95 transition-transform"
        @click="handleGetStarted"
      >
        Get Started
      </button>
      <button
        class="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"
        @click="handleShare"
      >
        Share App
      </button>
    </div>
  </main>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { App } from '@capacitor/app';

const appInfo = ref<{ name: string; version: string } | null>(null);

let backButtonListener: { remove: () => void } | null = null;

onMounted(async () => {
  // Get app info
  try {
    appInfo.value = await App.getInfo();
  } catch (e) {
    // Web fallback
    appInfo.value = { name: 'My Mobile App', version: '1.0.0' };
  }

  // Handle Android back button
  backButtonListener = await App.addListener('backButton', ({ canGoBack }) => {
    if (!canGoBack) {
      App.exitApp();
    } else {
      window.history.back();
    }
  });
});

onUnmounted(() => {
  backButtonListener?.remove();
});

function handleGetStarted() {
  // Navigate to onboarding or main app
  console.log('Get started clicked');
}

async function handleShare() {
  // We'll implement this with the Share plugin later
  console.log('Share clicked');
}
</script>

第 10 步:添加 Tailwind CSS

若要使样式生效,请在项目中添加 Tailwind CSS:

bun add tailwindcss @tailwindcss/vite

更新 nuxt.config.ts:

import tailwindcss from '@tailwindcss/vite';

export default defineNuxtConfig({
  compatibilityDate: '2025-01-15',
  devtools: { enabled: true },

  ssr: true,
  nitro: {
    preset: 'static',
  },

  css: ['~/assets/css/main.css'],

  vite: {
    plugins: [tailwindcss()],
  },
});

创建 app/assets/css/main.css:

@import 'tailwindcss';

: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;
}

第 11 步:添加 Share 插件

让我们来实现分享按钮的功能:

bun add @capacitor/share

更新 app/pages/index.vue 以使用 Share 插件:

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { App } from '@capacitor/app';
import { Share } from '@capacitor/share';

// ... existing code ...

async function handleShare() {
  try {
    await Share.share({
      title: 'Check out this app!',
      text: 'Built with Nuxt 4 and Capacitor 8',
      url: 'https://capacitorjs.com',
      dialogTitle: 'Share with friends',
    });
  } catch (e) {
    console.log('Share cancelled or failed:', e);
  }
}
</script>

同步并重新构建:

bun run mobile

项目结构

你的项目现在应该像这样:

my-mobile-app/
├── android/                  # Android native project
├── ios/                      # iOS native project
├── .output/
│   └── public/              # Static build output
├── app/
│   ├── assets/
│   │   └── css/
│   │       └── main.css
│   ├── pages/
│   │   └── index.vue
│   └── app.vue
├── capacitor.config.ts       # Capacitor configuration
├── nuxt.config.ts            # Nuxt configuration
├── package.json
└── ...

下一步

现在你已经拥有了一个可运行的 Nuxt 移动应用。接下来的操作如下:

核心配置

  • 应用图标: 替换以下目录中的默认图标 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 或 @capgo/capacitor-firebase-messaging 用于 iOS 和 Android 上的 Firebase Cloud Messaging
  • File System: 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 仓库 用于 Nuxt 特定配置。

修复 iOS 布局问题(视口、安全区域与水平溢出)

如果 iOS 上的内容看起来被裁剪、偏移或可水平滚动,仅靠添加更多 overflow-x: hidden 或单独调整 viewport 标签通常无法解决问题。请按顺序进行以下检查。

确保 viewport meta 标签已正确应用

在 nuxt.config.ts, 通过以下方式设置视口 app.head:

export default defineNuxtConfig({
  app: {
    head: {
      meta: [
        {
          name: 'viewport',
          content: 'width=device-width, initial-scale=1, viewport-fit=cover',
        },
      ],
    },
  },
});

只用一个根容器处理 iOS 安全区域

创建一个统一的 app shell,并在其中应用 safe area 内边距,而不是在多个嵌套组件中:

html,
body,
#__nuxt {
  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: '.output/public',
  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 标签本身。

热更新 (Over-the-Air Updates)

设置 Capgo 无需重新提交 App Store 即可推送更新:

bunx @capgo/cli init

故障排除

构建失败,提示 “Cannot find module” 运行 bun install 然后重试。

iOS:“未找到签名身份” 打开 Xcode,进入 Signing & Capabilities,然后选择你的开发团队。

Android:“未找到 SDK 位置” 创建 android/local.properties 配合 sdk.dir=/path/to/android/sdk

设备上未显示更改 请确保已运行 bun run mobile (请在更改后执行)。如需使用 live reload,请确认 IP 地址正确且开发服务器正在运行。

.output/public 为空或缺失 请确保已配置 nitro: { preset: 'static' } 中的 nuxt.config.ts 并运行 bun run generate.

资源

准备好发布应用了吗?了解 Capgo 如何帮你更快地交付更新 —— 注册免费账号 今天就开始。

继续阅读《使用 Capacitor 从零开始构建 Nuxt 移动应用》第 8 篇

如果你正在使用 使用 Capacitor 8 从零构建 Nuxt 移动应用 规划 CI/CD 自动化,并将其与 Capgo CI/CD 用于 Capgo CI/CD 中的产品工作流, Capgo Native Build 用于 Capgo Native Builds 中的产品工作流, Capgo 集成 用于 Capgo 集成中的产品工作流, CI/CD 集成 了解 CI/CD 集成的实现细节,以及 GitHub Actions 集成 有关 GitHub Actions 集成的实现细节。

为 Capacitor 应用提供 Live Updates

当 Web 层出现线上 Bug 时,通过 Capgo 发布修复,而不用等 App Store 审核好几天。用户会在后台收到更新,原生变更则仍走正常审核流程。

博客最新动态

Capgo 为你提供打造真正专业的移动应用所需的最有价值的洞察。