跳过主要内容
教程

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

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

马丁·多纳迪厄

马丁·多纳迪厄

内容营销人员

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

简介

想从头开始构建一个使用 Nuxt 的移动应用吗?本指南将带您完成从一开始就针对移动设备配置的新 Nuxt 4 项目的创建,然后将其打包为原生 iOS 和 Android 应用 Capacitor 8.

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

所需时间: ~30 分钟

您将构建:

  • 一个新的 Nuxt 4 项目,具有最新的目录结构
  • 针对移动设备的静态生成配置
  • Capacitor 8,带有必需的插件
  • 原生 iOS 和 Android 应用
  • 实时重载开发设置

已经有一个 Nuxt 应用程序?检查出 将 Nuxt 应用程序转换为移动应用 反之亦然。

先决条件

确保您安装了这些:

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

步骤 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

这种结构提供了更好的 app 和 server 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

这会创建 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: '.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: 添加分享插件

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

bun add @capacitor/share

更新 app/pages/index.vue 要使用分享插件,请执行以下操作:

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

添加更多功能

  • 相机: bun add @capacitor/camera
  • 地理位置: bun add @capacitor/geolocation
  • 推送通知: bun add @capacitor/push-notifications@capgo/capacitor-firebase-messaging 在 iOS 和 Android 上使用 Firebase Cloud Messaging
  • 文件系统: 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-transitionstailwind-capacitor 仓库

用于 Nuxt 特定设置。修复 iOS 布局问题(视口、安全区域和水平溢出)

如果内容看起来被裁切、偏移或水平滚动在iOS上,添加更多 overflow-x: hidden 或调整视口标签通常无法解决问题。按照以下顺序检查这些问题。

确保视口元标签被正确应用

nuxt.config.ts中设置视口 app.head:

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

处理iOS安全区域从一个根包装器中

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

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内。

在头部、模态和布局包装器中重复的安全区域填充通常会使UI看起来被裁切或过大。 @capgo/tailwind-capacitor@__CAPGO_KEEP_0__/tailwind-__CAPGO_KEEP_1__”,您可以使用类似工具来表达相同的填充 pt-safe pb-safe px-safe 在这个单一的 shell 中。

设置 Capacitor iOS contentInsetnever 首先

在,优先使用原生 inset 禁用并让 CSS(或 Native Navigation 的) capacitor.config.ts拥有安全区域: contentInsetMode: 'css'混合 __CAPGO_KEEP_0__ 的自动内容 inset 与 CSS

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

Mixing Capacitor’s automatic content inset with CSS env(safe-area-inset-*) 找到真正溢出的元素

通常的凶手是使用

, Tailwind 的元素 100vwMixing __CAPGO_KEEP_0__’s automatic content inset with CSS padding is a common cause of double spacing. 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, 重复的安全区域填充, 或者固定宽度容器 — 而不是视口元标签本身。

无线更新

设置 Capgo 推送更新而不需要重新提交应用商店:

bunx @capgo/cli init

故障排除

构建失败时出现“无法找到模块” 运行 bun install 并尝试再次。

iOS: “找不到签名身份” 打开 Xcode,转到 Signing &amp; Capabilities,选择您的开发团队。

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

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

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

资源

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

Keep going from Build a Nuxt Mobile App from Scratch with Capacitor 8

如果您正在使用 Build a Nuxt Mobile App from Scratch with Capacitor 8 来规划 CI/CD 自动化,连接它与 Capgo CI/CD 在 Capgo CI/CD 中的产品工作流程 Capgo 原生构建 在 Capgo 原生构建中 Capgo 集成 在 Capgo 集成中 CI/CD 集成 在 CI/CD 集成中 GitHub Actions Integration 为 GitHub Actions Integration 的实施细节。

实时更新Capacitor应用程序

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

立即开始

最新博客

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