capacitor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Capacitor: Cross-Platform Native Runtime

Capacitor:跨平台原生运行时

Capacitor is a cross-platform native runtime for building Web Native apps that run on iOS, Android, and the web from a single modern web codebase. It provides a consistent, web-focused API layer that bridges JavaScript to native device features via a plugin system.
Capacitor是一个跨平台原生运行时,用于构建可从单一现代Web代码库运行在iOS、Android和Web端的Web Native应用。它提供了一个一致的、以Web为中心的API层,通过插件系统将JavaScript桥接到原生设备功能。

Core Workflow

核心工作流

The canonical development loop is:
  1. Build web assets:
    npm run build
    (or
    ng build
    ,
    vite build
    , etc.)
  2. Sync to native projects:
    npx cap sync
    • Copies the web bundle into iOS and Android native projects
    • Installs/updates native plugin dependencies
    • Run this after every web build or plugin change
  3. Test on device:
    bash
    npx cap run ios
    npx cap run android
  4. Open native IDE when native changes are needed:
    bash
    npx cap open ios      # opens Xcode
    npx cap open android  # opens Android Studio
  5. Build a release binary:
    bash
    npx cap build android  # outputs signed AAB/APK
    npx cap build ios      # outputs IPA
Keep
@capacitor/core
,
@capacitor/ios
, and
@capacitor/android
on identical versions at all times. Update all together:
bash
npm i @capacitor/core @capacitor/ios @capacitor/android
npm i -D @capacitor/cli
标准开发循环如下:
  1. 构建Web资源
    npm run build
    (或
    ng build
    vite build
    等)
  2. 同步到原生项目
    npx cap sync
    • 将Web包复制到iOS和Android原生项目中
    • 安装/更新原生插件依赖
    • 每次Web构建或插件变更后都要运行此命令
  3. 在设备上测试
    bash
    npx cap run ios
    npx cap run android
  4. 需要原生变更时打开原生IDE
    bash
    npx cap open ios      # 打开Xcode
    npx cap open android  # 打开Android Studio
  5. 构建发布二进制文件
    bash
    npx cap build android  # 输出签名的AAB/APK
    npx cap build ios      # 输出IPA
请始终保持
@capacitor/core
@capacitor/ios
@capacitor/android
的版本完全一致。需同时更新所有包:
bash
npm i @capacitor/core @capacitor/ios @capacitor/android
npm i -D @capacitor/cli

Configuration

配置

Capacitor-level settings live in
capacitor.config.ts
(or
.json
). This file controls tooling only — not native runtime behavior. Key fields:
FieldPurpose
appId
Bundle identifier (e.g.
com.example.app
)
appName
Display name
webDir
Output directory of the web build (e.g.
dist
,
build
,
www
)
server.url
Override for live reload (remove before committing)
Platform-specific runtime configuration is done in native IDEs:
ios/App/App/Info.plist
and
AndroidManifest.xml
for Android. Do not attempt to manage those via the Capacitor config file.
Capacitor级别的设置存储在
capacitor.config.ts
(或
.json
)中。此文件仅控制工具配置——不影响原生运行时行为。关键字段:
字段用途
appId
包标识符(例如
com.example.app
appName
应用显示名称
webDir
Web构建的输出目录(例如
dist
build
www
server.url
热重载的替代地址(提交前请移除)
平台特定的运行时配置需在原生IDE中完成:iOS为
ios/App/App/Info.plist
,Android为
AndroidManifest.xml
。请勿尝试通过Capacitor配置文件管理这些内容。

Plugins

插件

Capacitor plugins expose native APIs to JavaScript. Three sources exist:
  • Official plugins (
    @capacitor/*
    ) — maintained by the Capacitor team, covering Camera, Filesystem, Geolocation, Push Notifications, Preferences, etc.
  • Community plugins (
    @capacitor-community/*
    ) — curated third-party ecosystem
  • Cordova plugins — compatibility layer; prefer Capacitor-native equivalents
Install a plugin, then sync:
bash
npm install @capacitor/camera
npx cap sync
Always check whether a plugin requires additional native configuration (entitlements on iOS, permissions in
AndroidManifest.xml
). The plugin's README will specify.
Capacitor插件将原生API暴露给JavaScript。插件来源有三种:
  • 官方插件
    @capacitor/*
    )——由Capacitor团队维护,涵盖相机、文件系统、地理定位、推送通知、偏好设置等功能
  • 社区插件
    @capacitor-community/*
    )——经过筛选的第三方生态插件
  • Cordova插件——兼容层;优先选择Capacitor原生等效插件
安装插件后执行同步:
bash
npm install @capacitor/camera
npx cap sync
请务必检查插件是否需要额外的原生配置(iOS的权限 entitlement,AndroidManifest.xml中的权限)。插件的README会详细说明。

Mocking Plugins in Tests

测试中模拟插件

Capacitor plugins are JavaScript proxies; wrapping a proxy in another proxy fails. Use manual mocks instead.
Jest — place stubs under
__mocks__/@capacitor/
:
ts
// __mocks__/@capacitor/preferences.ts
export const Preferences = {
  async get(data: { key: string }) { return { value: undefined }; },
  async set(_data: { key: string; value: string }) {},
  async remove(_data: { key: string }) {},
  async clear() {},
};
Jest auto-discovers files from
__mocks__/
before
node_modules
.
Jasmine/Angular — add a
paths
mapping in
tsconfig.spec.json
:
json
"paths": {
  "@capacitor/*": ["__mocks__/@capacitor/*"]
}
Note:
paths
in
tsconfig.spec.json
replaces (does not merge with) the base
tsconfig.json
paths — include all existing entries.
Capacitor插件是JavaScript代理;在另一个代理中包装代理会失败。请改用手动模拟
Jest——在
__mocks__/@capacitor/
目录下放置存根文件:
ts
// __mocks__/@capacitor/preferences.ts
export const Preferences = {
  async get(data: { key: string }) { return { value: undefined }; },
  async set(_data: { key: string; value: string }) {},
  async remove(_data: { key: string }) {},
  async clear() {},
};
Jest会在
node_modules
之前自动发现
__mocks__/
目录下的文件。
Jasmine/Angular——在
tsconfig.spec.json
中添加
paths
映射:
json
"paths": {
  "@capacitor/*": ["__mocks__/@capacitor/*"]
}
注意:
tsconfig.spec.json
中的
paths
会替换(而非合并)基础
tsconfig.json
中的paths——请包含所有现有条目。

Storage

存储

Do not rely on
localStorage
or
IndexedDB
as primary storage on mobile. The OS reclaims both when storage is low. IndexedDB on iOS is not persisted by default.
Use caseRecommended solution
Small key/value data (settings, tokens)
@capacitor/preferences
Large datasets / SQL queriesSQLite plugin (
capacitor-sqlite
)
Sensitive values (encryption keys, auth tokens)iOS Keychain / Android Keystore via a plugin
ts
import { Preferences } from '@capacitor/preferences';

// Write
await Preferences.set({ key: 'theme', value: 'dark' });

// Read
const { value } = await Preferences.get({ key: 'theme' });

// Remove
await Preferences.remove({ key: 'theme' });
Preferences
values are stored natively and survive app updates and low-storage eviction.
在移动设备上,请勿依赖
localStorage
IndexedDB
作为主要存储方式。当存储空间不足时,操作系统会回收这两种存储的数据。iOS上的IndexedDB默认不持久化。
使用场景推荐方案
小型键值对数据(设置、令牌)
@capacitor/preferences
大型数据集/SQL查询SQLite插件(
capacitor-sqlite
敏感值(加密密钥、认证令牌)通过插件使用iOS Keychain / Android Keystore
ts
import { Preferences } from '@capacitor/preferences';

// 写入
await Preferences.set({ key: 'theme', value: 'dark' });

// 读取
const { value } = await Preferences.get({ key: 'theme' });

// 删除
await Preferences.remove({ key: 'theme' });
Preferences
的值存储在原生端,可在应用更新和低存储回收后保留。

Security

安全

Secrets and API Keys

密钥与API密钥

Never embed secrets in web app code. The JavaScript bundle ships inside the app binary and is trivially extractable. Move secret-dependent logic server-side (serverless function or backend API). If a token must exist on device (e.g. auth token), store it only in memory or in the native Keychain/Keystore — never in
localStorage
or
Preferences
unencrypted.
切勿在Web应用代码中嵌入密钥。JavaScript包会随应用二进制文件一起分发,极易被提取。将依赖密钥的逻辑移至服务器端(无服务器函数或后端API)。如果令牌必须存放在设备上(例如认证令牌),请仅将其存储在内存中或原生Keychain/Keystore中——切勿未加密存储在
localStorage
Preferences
中。

Network

网络

Only make requests to
https://
endpoints. Never use
http://
in production builds.
仅向
https://
端点发起请求。生产构建中切勿使用
http://

Content Security Policy

内容安全策略

Add a CSP
<meta>
tag in
index.html
to restrict resource loading:
html
<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; connect-src 'self' https://api.example.com"
/>
index.html
中添加CSP
<meta>
标签以限制资源加载:
html
<meta
  http-equiv="Content-Security-Policy"
  content="default-src 'self'; connect-src 'self' https://api.example.com"
/>

oAuth2 / Deep Link Authentication

OAuth2 / 深度链接认证

Custom URL schemes (e.g.
myapp://
) are not domain-controlled and can be intercepted by a malicious app. Never pass sensitive tokens through a custom scheme. Use Universal Links (iOS) or App Links (Android) for auth callbacks, and always enable PKCE in oAuth2 flows.
自定义URL方案(例如
myapp://
)不受域名控制,可能被恶意应用拦截。切勿通过自定义方案传递敏感令牌。请使用Universal Links(iOS)或App Links(Android)进行认证回调,并始终在OAuth2流程中启用PKCE

Deep Links (Universal Links / App Links)

深度链接(Universal Links / App Links)

Deep links allow HTTPS URLs to open specific screens inside the native app. Prefer Universal/App Links over custom URL schemes — they require verified web domain ownership.
深度链接允许HTTPS URL打开原生应用内的特定页面。优先使用Universal/App Links而非自定义URL方案——它们需要验证Web域名所有权。

Listen for Incoming Links

监听传入链接

Register the listener early (e.g. app bootstrap):
ts
import { App } from '@capacitor/app';

App.addListener('appUrlOpen', (event) => {
  const path = new URL(event.url).pathname;
  // hand off to your router
  router.navigate(path);
});
尽早注册监听器(例如应用启动时):
ts
import { App } from '@capacitor/app';

App.addListener('appUrlOpen', (event) => {
  const path = new URL(event.url).pathname;
  // 传递给你的路由
  router.navigate(path);
});

Required Setup (both platforms)

必要设置(双平台)

  1. Host a site association file at
    https://yourdomain.com/.well-known/
    :
    • iOS:
      apple-app-site-association
      (no extension, JSON)
    • Android:
      assetlinks.json
  2. Configure the native app:
    • iOS: enable Associated Domains in Xcode (
      applinks:yourdomain.com
      )
    • Android: add
      intent-filter
      with
      android:autoVerify="true"
      in
      AndroidManifest.xml
See
references/security-and-deeplinks.md
for complete file formats and intent filter XML.
  1. https://yourdomain.com/.well-known/
    托管站点关联文件:
    • iOS:
      apple-app-site-association
      (无扩展名,JSON格式)
    • Android:
      assetlinks.json
  2. 配置原生应用:
    • iOS:在Xcode中启用关联域名(
      applinks:yourdomain.com
    • Android:在
      AndroidManifest.xml
      中添加带有
      android:autoVerify="true"
      intent-filter
完整的文件格式和intent filter XML请参考
references/security-and-deeplinks.md

Live Reload (Development Only)

热重载(仅开发环境)

Live reload reloads the WebView when web source files change — no native rebuild required.
With Ionic CLI (recommended):
bash
npm install -g @ionic/cli native-run
ionic cap run ios -l --external
ionic cap run android -l --external
Without Ionic CLI — add a
server
entry to
capacitor.config.json
:
json
"server": {
  "url": "http://192.168.1.68:8100",
  "cleartext": true
}
Run
npx cap copy
to push the config update, then launch from the native IDE.
Never commit the
server
config to source control.
Remove it before building for release.
当Web源文件变更时,热重载会重新加载WebView——无需重新构建原生应用。
使用Ionic CLI(推荐):
bash
npm install -g @ionic/cli native-run
ionic cap run ios -l --external
ionic cap run android -l --external
不使用Ionic CLI——在
capacitor.config.json
中添加
server
条目:
json
"server": {
  "url": "http://192.168.1.68:8100",
  "cleartext": true
}
运行
npx cap copy
推送配置更新,然后从原生IDE启动应用。
切勿将
server
配置提交到源代码管理。
构建发布版本前请移除它。

Quick Reference

快速参考

TaskCommand
Sync web build to native
npx cap sync
Copy web assets only
npx cap copy
Open iOS project
npx cap open ios
Open Android project
npx cap open android
Run on device
npx cap run ios
/
npx cap run android
Build release binary
npx cap build ios
/
npx cap build android
Update Capacitor
npm i @capacitor/core @capacitor/ios @capacitor/android
任务命令
将Web构建同步到原生端
npx cap sync
仅复制Web资源
npx cap copy
打开iOS项目
npx cap open ios
打开Android项目
npx cap open android
在设备上运行
npx cap run ios
/
npx cap run android
构建发布二进制文件
npx cap build ios
/
npx cap build android
更新Capacitor
npm i @capacitor/core @capacitor/ios @capacitor/android

Additional Resources

额外资源

  • references/plugins-and-storage.md
    — Plugin installation patterns, Preferences API reference, SQLite options, and testing stubs in detail
  • references/security-and-deeplinks.md
    — CSP patterns, Keychain/Keystore guidance, full Universal Links / App Links file formats, PKCE requirements
  • references/plugins-and-storage.md
    ——插件安装模式、Preferences API参考、SQLite选项以及详细的测试存根说明
  • references/security-and-deeplinks.md
    ——CSP模式、Keychain/Keystore使用指南、完整的Universal Links / App Links文件格式、PKCE要求