"一步一步地创建一个新的 Nuxt 4 项目,并将其转换为使用 __CAPGO_KEEP_0__ 8 的原生 iOS 和 Android 移动应用。适合从头开始"
教程

Build a Nuxt Mobile App from Scratch with Capacitor 8

Step-by-step guide to creating a new Nuxt 4 project and turning it into native iOS and Android mobile apps using Capacitor 8. Perfect for starting fresh with mobile-first Vue development.

文章来源

马丁·多纳迪

作者

瓦莱里亚

审稿人

乔丹

编辑

Build a Nuxt Mobile App from Scratch with Capacitor 8

介绍

想从头开始构建一个使用 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 开发)
  • 安卓 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/ directory:

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

This structure provides better separation between app and server code.

__CAPGO_KEEP_0__ 需要静态 HTML/JS/CSS 文件。配置 Nuxt 以进行静态生成在

Capacitor 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 目录包含您的静态文件。

Step 4: Install Capacitor 8

Install the Capacitor core packages:

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

初始化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 步:添加本机平台

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

bun add @capacitor/ios @capacitor/android

安装平台包:

bunx cap add ios
bunx cap add android

这会创建 ios 生成本机项目: android 和

上下文:Capgo 营销网站。角色:短 UI 标签或导航项。见于:信任.astro 页面。消息键 `and`(和)。

包含本机项目的目录。

bun run mobile

第 7 步:构建和运行本机项目:

bun run mobile:ios

或 Android 模拟器:

bun run mobile:android

在 Xcode (iOS) 中:

  1. 选择设备下拉菜单中的模拟器
  2. 点击播放按钮或按 Cmd + R

在 Android Studio 中:

  1. 等待 Gradle 完成同步
  2. 选择设备下拉菜单中的模拟器
  3. 点击运行按钮或按 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中重建

Now edits to your Nuxt code will hot-reload on the device.

第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.xcassets 和 android/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-transitions, 和 tailwind-capacitor 仓库 为 Nuxt 特定设置。

解决 iOS 布局问题(视口、安全区域和水平溢出)

如果内容在 iOS 上被裁切、偏移或水平滚动,仅添加或调整视口标签通常无法解决问题。按照以下顺序检查这些问题。 overflow-x: hidden 确保视口元标签已正确应用

在

中设置视口 nuxt.config.ts处理 iOS 安全区域 app.head:

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

从根包装器中只处理一次安全区域

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

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

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

设置CapacitoriOS contentInset 到 never 首先

在 capacitor.config.ts,更倾向于使用原生边距禁用,并让CSS(或Native Navigation的) contentInsetMode: 'css')来控制安全区域:

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

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

找到真实的溢出元素

通常的罪魁祸首是使用 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中,推送更新无需重新提交应用商店:

在Capgo中,构建失败时会出现“无法找到模块” 在Capgo中,推送更新无需重新提交应用商店:

安卓:“SDK”位置未找到 iOS:找不到签名身份 android/local.properties with sdk.dir=/path/to/android/sdk

Android:__CAPGO_KEEP_0__位置未找到 创建 bun run mobile 在修改后。为了实时重载,请确保 IP 地址正确并且开发服务器正在运行。

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

资源

准备好发布应用程序?了解如何 Capgo 可以帮助您更快地交付更新 — 注册免费账户 今天。

继续 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动作集成 为GitHub动作集成的实现细节

为 Capacitor 应用实时更新

当 web 层 bug 活跃时,通过 Capgo 将修复推送到用户,而不是等待几天的 app 商店审批。用户在后台接收更新,而原生变化保持在正常审批路径中。

来自马丁的人性化支持

立即开始

最新博客文章

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