capacitor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCapacitor: 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:
- Build web assets: (or
npm run build,ng build, etc.)vite build - 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
- Test on device:
bash
npx cap run ios npx cap run android - Open native IDE when native changes are needed:
bash
npx cap open ios # opens Xcode npx cap open android # opens Android Studio - Build a release binary:
bash
npx cap build android # outputs signed AAB/APK npx cap build ios # outputs IPA
Keep , , and on identical versions at all times. Update all together:
@capacitor/core@capacitor/ios@capacitor/androidbash
npm i @capacitor/core @capacitor/ios @capacitor/android
npm i -D @capacitor/cli标准开发循环如下:
- 构建Web资源:(或
npm run build、ng build等)vite build - 同步到原生项目:
npx cap sync- 将Web包复制到iOS和Android原生项目中
- 安装/更新原生插件依赖
- 每次Web构建或插件变更后都要运行此命令
- 在设备上测试:
bash
npx cap run ios npx cap run android - 需要原生变更时打开原生IDE:
bash
npx cap open ios # 打开Xcode npx cap open android # 打开Android Studio - 构建发布二进制文件:
bash
npx cap build android # 输出签名的AAB/APK npx cap build ios # 输出IPA
请始终保持、和的版本完全一致。需同时更新所有包:
@capacitor/core@capacitor/ios@capacitor/androidbash
npm i @capacitor/core @capacitor/ios @capacitor/android
npm i -D @capacitor/cliConfiguration
配置
Capacitor-level settings live in (or ). This file controls tooling only — not native runtime behavior. Key fields:
capacitor.config.ts.json| Field | Purpose |
|---|---|
| Bundle identifier (e.g. |
| Display name |
| Output directory of the web build (e.g. |
| Override for live reload (remove before committing) |
Platform-specific runtime configuration is done in native IDEs: and for Android. Do not attempt to manage those via the Capacitor config file.
ios/App/App/Info.plistAndroidManifest.xmlCapacitor级别的设置存储在(或)中。此文件仅控制工具配置——不影响原生运行时行为。关键字段:
capacitor.config.ts.json| 字段 | 用途 |
|---|---|
| 包标识符(例如 |
| 应用显示名称 |
| Web构建的输出目录(例如 |
| 热重载的替代地址(提交前请移除) |
平台特定的运行时配置需在原生IDE中完成:iOS为,Android为。请勿尝试通过Capacitor配置文件管理这些内容。
ios/App/App/Info.plistAndroidManifest.xmlPlugins
插件
Capacitor plugins expose native APIs to JavaScript. Three sources exist:
- Official plugins () — maintained by the Capacitor team, covering Camera, Filesystem, Geolocation, Push Notifications, Preferences, etc.
@capacitor/* - Community plugins () — curated third-party ecosystem
@capacitor-community/* - Cordova plugins — compatibility layer; prefer Capacitor-native equivalents
Install a plugin, then sync:
bash
npm install @capacitor/camera
npx cap syncAlways check whether a plugin requires additional native configuration (entitlements on iOS, permissions in ). The plugin's README will specify.
AndroidManifest.xmlCapacitor插件将原生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 before .
__mocks__/node_modulesJasmine/Angular — add a mapping in :
pathstsconfig.spec.jsonjson
"paths": {
"@capacitor/*": ["__mocks__/@capacitor/*"]
}Note: in replaces (does not merge with) the base paths — include all existing entries.
pathstsconfig.spec.jsontsconfig.jsonCapacitor插件是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.jsonpathsjson
"paths": {
"@capacitor/*": ["__mocks__/@capacitor/*"]
}注意:中的会替换(而非合并)基础中的paths——请包含所有现有条目。
tsconfig.spec.jsonpathstsconfig.jsonStorage
存储
Do not rely on or as primary storage on mobile. The OS reclaims both when storage is low. IndexedDB on iOS is not persisted by default.
localStorageIndexedDB| Use case | Recommended solution |
|---|---|
| Small key/value data (settings, tokens) | |
| Large datasets / SQL queries | SQLite plugin ( |
| 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在移动设备上,请勿依赖或作为主要存储方式。当存储空间不足时,操作系统会回收这两种存储的数据。iOS上的IndexedDB默认不持久化。
localStorageIndexedDB| 使用场景 | 推荐方案 |
|---|---|
| 小型键值对数据(设置、令牌) | |
| 大型数据集/SQL查询 | 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' });PreferencesSecurity
安全
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 or unencrypted.
localStoragePreferences切勿在Web应用代码中嵌入密钥。JavaScript包会随应用二进制文件一起分发,极易被提取。将依赖密钥的逻辑移至服务器端(无服务器函数或后端API)。如果令牌必须存放在设备上(例如认证令牌),请仅将其存储在内存中或原生Keychain/Keystore中——切勿未加密存储在或中。
localStoragePreferencesNetwork
网络
Only make requests to endpoints. Never use in production builds.
https://http://仅向端点发起请求。生产构建中切勿使用。
https://http://Content Security Policy
内容安全策略
Add a CSP tag in to restrict resource loading:
<meta>index.htmlhtml
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; connect-src 'self' https://api.example.com"
/>在中添加CSP 标签以限制资源加载:
index.html<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. ) 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.
myapp://自定义URL方案(例如 )不受域名控制,可能被恶意应用拦截。切勿通过自定义方案传递敏感令牌。请使用Universal Links(iOS)或App Links(Android)进行认证回调,并始终在OAuth2流程中启用PKCE。
myapp://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)
必要设置(双平台)
- Host a site association file at :
https://yourdomain.com/.well-known/- iOS: (no extension, JSON)
apple-app-site-association - Android:
assetlinks.json
- iOS:
- Configure the native app:
- iOS: enable Associated Domains in Xcode ()
applinks:yourdomain.com - Android: add with
intent-filterinandroid:autoVerify="true"AndroidManifest.xml
- iOS: enable Associated Domains in Xcode (
See for complete file formats and intent filter XML.
references/security-and-deeplinks.md- 在托管站点关联文件:
https://yourdomain.com/.well-known/- iOS:(无扩展名,JSON格式)
apple-app-site-association - Android:
assetlinks.json
- iOS:
- 配置原生应用:
- iOS:在Xcode中启用关联域名()
applinks:yourdomain.com - Android:在中添加带有
AndroidManifest.xml的android:autoVerify="true"intent-filter
- iOS:在Xcode中启用关联域名(
完整的文件格式和intent filter XML请参考。
references/security-and-deeplinks.mdLive 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 --externalWithout Ionic CLI — add a entry to :
servercapacitor.config.jsonjson
"server": {
"url": "http://192.168.1.68:8100",
"cleartext": true
}Run to push the config update, then launch from the native IDE.
npx cap copyNever commit the config to source control. Remove it before building for release.
server当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.jsonserverjson
"server": {
"url": "http://192.168.1.68:8100",
"cleartext": true
}运行推送配置更新,然后从原生IDE启动应用。
npx cap copy切勿将配置提交到源代码管理。 构建发布版本前请移除它。
serverQuick Reference
快速参考
| Task | Command |
|---|---|
| Sync web build to native | |
| Copy web assets only | |
| Open iOS project | |
| Open Android project | |
| Run on device | |
| Build release binary | |
| Update Capacitor | |
| 任务 | 命令 |
|---|---|
| 将Web构建同步到原生端 | |
| 仅复制Web资源 | |
| 打开iOS项目 | |
| 打开Android项目 | |
| 在设备上运行 | |
| 构建发布二进制文件 | |
| 更新Capacitor | |
Additional Resources
额外资源
- — Plugin installation patterns, Preferences API reference, SQLite options, and testing stubs in detail
references/plugins-and-storage.md - — CSP patterns, Keychain/Keystore guidance, full Universal Links / App Links file formats, PKCE requirements
references/security-and-deeplinks.md
- ——插件安装模式、Preferences API参考、SQLite选项以及详细的测试存根说明
references/plugins-and-storage.md - ——CSP模式、Keychain/Keystore使用指南、完整的Universal Links / App Links文件格式、PKCE要求
references/security-and-deeplinks.md