Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问许可证需确认审计通过

capacitor-best-practices电容器最佳实践

Agent Skill

capacitor-best-practices 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

14,566

周安装

595

GitHub Stars

30

下载量

4,712
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:capacitor-best-practices(电容器最佳实践)
来源仓库:https://github.com/cap-go/capacitor-skills
仓库路径:skills/capacitor-best-practices
安装命令:
npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-best-practices

简介

用于构建可投入生产的电容器应用的综合指南。

  • 涵盖项目结构、配置管理、插件安装模式以及 iOS 和 Android 的本机项目设置
  • 强调关键实践:保持 Capacitor 包同步、使用前检查插件可用性、延迟加载插件以及敏感数据的安全存储
  • 包括性能优化策略,例如批处理桥接调用、硬件加速以及具有质量/大小限制的图像优化
  • 提供安全最佳实践,包括证书固定、根/越狱检测以及所有插件调用的正确错误处理
  • 包含使用具有后台下载模式的 Capacitor Updater 的部署清单和实时更新策略

SKILL.md

Capacitor Best Practices

Comprehensive guidelines for building production-ready Capacitor applications.

When to Use This Skill

  • Setting up a new Capacitor project
  • Reviewing Capacitor app architecture
  • Optimizing app performance
  • Implementing security measures
  • Preparing for app store submission

Project Structure

Recommended Directory Layout

my-app/
├── src/                      # Web app source
├── android/                  # Android native project
├── ios/                      # iOS native project
├── capacitor.config.ts       # Capacitor configuration
├── package.json
└── tsconfig.json

Configuration Best Practices

capacitor.config.ts (CORRECT):

import type { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.company.app',
  appName: 'My App',
  webDir: 'dist',
  server: {
    // Only enable for development
    ...(process.env.NODE_ENV === 'development' && {
      url: 'http://localhost:5173',
      cleartext: true,
    }),
  },
  plugins: {
    SplashScreen: {
      launchAutoHide: false,
    },
  },
};

export default config;

capacitor.config.json (AVOID):

{
  "server": {
    "url": "http://localhost:5173",
    "cleartext": true
  }
}

*Never commit development server URLs to production*

Plugin Usage

CRITICAL: Always Use Latest Capacitor

Keep Capacitor core packages in sync:

npm install @capacitor/core@latest @capacitor/cli@latest
npm install @capacitor/ios@latest @capacitor/android@latest
npx cap sync

Plugin Installation Pattern

CORRECT:

# 1. Install the package
npm install @capgo/capacitor-native-biometric

# 2. Sync native projects
npx cap sync

# 3. For iOS: Install pods (or use SPM)
cd ios/App && pod install && cd ../..

INCORRECT:

# Missing sync step
npm install @capgo/capacitor-native-biometric
# App crashes because native code not linked

Plugin Initialization

CORRECT - Check availability before use:

import { NativeBiometric, BiometryType } from '@capgo/capacitor-native-biometric';

async function authenticate() {
  const { isAvailable, biometryType } = await NativeBiometric.isAvailable();

  if (!isAvailable) {
    // Fallback to password
    return authenticateWithPassword();
  }

  try {
    await NativeBiometric.verifyIdentity({
      reason: 'Authenticate to access your account',
      title: 'Biometric Login',
    });
    return true;
  } catch (error) {
    // User cancelled or biometric failed
    return false;
  }
}

INCORRECT - No availability check:

// Will crash if biometrics not available
await NativeBiometric.verifyIdentity({ reason: 'Login' });

Performance Optimization

CRITICAL: Lazy Load Plugins

CORRECT - Dynamic imports:

// Only load when needed
async function scanDocument() {
  const { DocumentScanner } = await import('@capgo/capacitor-document-scanner');
  return DocumentScanner.scanDocument();
}

INCORRECT - Import everything at startup:

// Increases initial bundle size
import { DocumentScanner } from '@capgo/capacitor-document-scanner';
import { NativeBiometric } from '@capgo/capacitor-native-biometric';
import { Camera } from '@capacitor/camera';
// ... 20 more plugins

HIGH: Optimize WebView Performance

CORRECT - Use hardware acceleration:

<!-- android/app/src/main/AndroidManifest.xml -->
<application
    android:hardwareAccelerated="true"
    android:largeHeap="true">
<!-- ios/App/App/Info.plist -->
<key>UIViewGroupOpacity</key>
<false/>

HIGH: Minimize Bridge Calls

CORRECT - Batch operations:

// Single call with batch data
await Storage.set({
  key: 'userData',
  value: JSON.stringify({ name, email, preferences }),
});

INCORRECT - Multiple bridge calls:

// Each call crosses the JS-native bridge
await Storage.set({ key: 'name', value: name });
await Storage.set({ key: 'email', value: email });
await Storage.set({ key: 'preferences', value: JSON.stringify(preferences) });

MEDIUM: Image Optimization

CORRECT:

import { Camera, CameraResultType } from '@capacitor/camera';

const photo = await Camera.getPhoto({
  quality: 80,           // Not 100
  width: 1024,           // Reasonable max
  resultType: CameraResultType.Uri,  // Not Base64 for large images
  correctOrientation: true,
});

INCORRECT:

const photo = await Camera.getPhoto({
  quality: 100,
  resultType: CameraResultType.Base64,  // Memory intensive
  // No size limits
});

Security Best Practices

CRITICAL: Secure Storage

CORRECT - Use secure storage for sensitive data:

import { NativeBiometric } from '@capgo/capacitor-native-biometric';

// Store credentials securely
await NativeBiometric.setCredentials({
  username: 'user@example.com',
  password: 'secret',
  server: 'api.myapp.com',
});

// Retrieve with biometric verification
const credentials = await NativeBiometric.getCredentials({
  server: 'api.myapp.com',
});

INCORRECT - Plain storage:

import { Preferences } from '@capacitor/preferences';

// NEVER store sensitive data in plain preferences
await Preferences.set({
  key: 'password',
  value: 'secret',  // Stored in plain text!
});

CRITICAL: Certificate Pinning

For production apps handling sensitive data:

// capacitor.config.ts
const config: CapacitorConfig = {
  plugins: {
    CapacitorHttp: {
      enabled: true,
    },
  },
  server: {
    // Disable cleartext in production
    cleartext: false,
  },
};

HIGH: Root/Jailbreak Detection

import { IsRoot } from '@capgo/capacitor-is-root';

async function checkDeviceSecurity() {
  const { isRooted } = await IsRoot.isRooted();

  if (isRooted) {
    // Show warning or restrict functionality
    showSecurityWarning('Device appears to be rooted/jailbroken');
  }
}

HIGH: App Tracking Transparency (iOS)

import { AppTrackingTransparency } from '@capgo/capacitor-app-tracking-transparency';

async function requestTracking() {
  const { status } = await AppTrackingTransparency.requestPermission();

  if (status === 'authorized') {
    // Enable analytics
  }
}

Error Handling

CRITICAL: Always Handle Plugin Errors

CORRECT:

import { Camera, CameraResultType } from '@capacitor/camera';

async function takePhoto() {
  try {
    const image = await Camera.getPhoto({
      quality: 90,
      resultType: CameraResultType.Uri,
    });
    return image;
  } catch (error) {
    if (error.message === 'User cancelled photos app') {
      // User cancelled, not an error
      return null;
    }
    if (error.message.includes('permission')) {
      // Permission denied
      showPermissionDialog();
      return null;
    }
    // Unexpected error
    console.error('Camera error:', error);
    throw error;
  }
}

INCORRECT:

// No error handling
const image = await Camera.getPhoto({ quality: 90 });

Live Updates

Using Capacitor Updater

import { CapacitorUpdater } from '@capgo/capacitor-updater';

// Notify when app is ready
CapacitorUpdater.notifyAppReady();

// Listen for updates
CapacitorUpdater.addListener('updateAvailable', async (update) => {
  // Download in background
  const bundle = await CapacitorUpdater.download({
    url: update.url,
    version: update.version,
  });

  // Apply on next app start
  await CapacitorUpdater.set(bundle);
});

Update Strategy

CORRECT - Background download, apply on restart:

// Download silently
const bundle = await CapacitorUpdater.download({ url, version });

// User continues using app...

// Apply when they close/reopen
await CapacitorUpdater.set(bundle);

INCORRECT - Interrupt user:

// Don't force reload while user is active
const bundle = await CapacitorUpdater.download({ url, version });
await CapacitorUpdater.reload();  // Disrupts user

Native Project Management

iOS: Use Swift Package Manager (SPM)

Modern approach - prefer SPM over CocoaPods:

# Podfile - Remove plugin pods, use SPM instead
target 'App' do
  capacitor_pods
  # Plugin dependencies via SPM in Xcode
end

Android: Gradle Configuration

// android/app/build.gradle
android {
    defaultConfig {
        minSdkVersion 22
        targetSdkVersion 34
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

Testing

Plugin Mocking

// Mock for web testing
jest.mock('@capgo/capacitor-native-biometric', () => ({
  NativeBiometric: {
    isAvailable: jest.fn().mockResolvedValue({
      isAvailable: true,
      biometryType: 'touchId',
    }),
    verifyIdentity: jest.fn().mockResolvedValue({}),
  },
}));

Platform Detection

import { Capacitor } from '@capacitor/core';

if (Capacitor.isNativePlatform()) {
  // Native-specific code
} else {
  // Web fallback
}

// Or check specific platform
if (Capacitor.getPlatform() === 'ios') {
  // iOS-specific code
}

Deployment Checklist

  • Remove development server URLs from config
  • Enable ProGuard for Android release builds
  • Set appropriate iOS deployment target
  • Test on real devices, not just simulators
  • Verify all permissions are declared
  • Test with poor network conditions
  • Verify deep links work correctly
  • Test app backgrounding/foregrounding
  • Verify push notifications work
  • Test biometric authentication edge cases

Resources

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.01%
按下载量换算1,650

Claude

33.1%
按下载量换算1,560

Cursor

18.42%
按下载量换算868

Gemini CLI

10.21%
按下载量换算481

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills