cordova-to-capacitor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCordova to Capacitor Migration
从Cordova迁移到Capacitor
Step-by-step guide for migrating from Apache Cordova/PhoneGap to Capacitor.
从Apache Cordova/PhoneGap迁移到Capacitor的分步指南。
When to Use This Skill
何时使用本指南
- Migrating an existing Cordova app to Capacitor
- Converting PhoneGap projects to Capacitor
- Understanding Cordova vs Capacitor differences
- Finding Capacitor equivalents for Cordova plugins
- Modernizing hybrid mobile apps
- 将现有Cordova应用迁移到Capacitor
- 将PhoneGap项目转换为Capacitor项目
- 了解Cordova与Capacitor的差异
- 寻找Cordova插件对应的Capacitor替代方案
- 现代化混合移动应用
Why Migrate from Cordova?
为何从Cordova迁移?
| Aspect | Cordova | Capacitor |
|---|---|---|
| Native IDE | Builds via CLI | First-class Xcode/Android Studio |
| Plugin Management | Separate ecosystem | npm packages |
| Updates | Full app store review | Live updates with Capgo |
| Web App Platform | Any | Any (React, Vue, Angular, etc.) |
| Maintenance | Slowing down | Active development |
| TypeScript | Limited | Full support |
| Modern APIs | Older patterns | Modern Promise-based APIs |
| 维度 | Cordova | Capacitor |
|---|---|---|
| 原生IDE | 通过CLI构建 | 原生支持Xcode/Android Studio |
| 插件管理 | 独立生态系统 | npm包管理 |
| 更新机制 | 需要完整应用商店审核 | 搭配Capgo实现实时更新 |
| Web应用支持 | 任意Web框架 | 任意Web框架(React、Vue、Angular等) |
| 维护状态 | 维护进度放缓 | 持续活跃开发 |
| TypeScript支持 | 有限支持 | 全面支持 |
| API风格 | 旧版模式 | 现代Promise式API |
Migration Process Overview
迁移流程概述
Step 1: Assess Your Current App
步骤1:评估当前应用
Check Cordova version:
bash
cordova --version
cordova platform versionList installed plugins:
bash
cordova plugin listReview config.xml:
bash
cat config.xml检查Cordova版本:
bash
cordova --version
cordova platform version列出已安装插件:
bash
cordova plugin list查看config.xml配置:
bash
cat config.xmlStep 2: Install Capacitor
步骤2:安装Capacitor
In your existing Cordova project:
bash
undefined在现有Cordova项目中执行:
bash
undefinedInstall Capacitor
安装Capacitor
bun add @capacitor/core @capacitor/cli
bun add @capacitor/core @capacitor/cli
Initialize Capacitor
初始化Capacitor
bunx cap init
**When prompted:**
- **App name**: Your app's display name
- **App ID**: Use the same ID from config.xml (e.g., `com.company.app`)
- **Web directory**: Usually `www` for Cordova projectsbunx cap init
**初始化时的提示项:**
- **App name**:应用的显示名称
- **App ID**:使用config.xml中的相同ID(例如:`com.company.app`)
- **Web directory**:Cordova项目通常为`www`Step 3: Add Platforms
步骤3:添加平台
Capacitor doesn't modify web assets. Add platforms separately:
bash
undefinedCapacitor不会修改Web资源,需单独添加平台:
bash
undefinedAdd iOS platform
添加iOS平台
bun add @capacitor/ios
bunx cap add ios
bun add @capacitor/ios
bunx cap add ios
Add Android platform
添加Android平台
bun add @capacitor/android
bunx cap add android
This creates:
- `ios/` directory with Xcode project
- `android/` directory with Android Studio projectbun add @capacitor/android
bunx cap add android
执行后会生成:
- `ios/`目录,包含Xcode项目
- `android/`目录,包含Android Studio项目Step 4: Migrate Plugins
步骤4:迁移插件
CRITICAL: Check plugin compatibility first.
关键:先检查插件兼容性
Core Cordova Plugins → Capacitor Equivalents
核心Cordova插件 → Capacitor替代方案
| Cordova Plugin | Capacitor Equivalent | Install Command |
|---|---|---|
| cordova-plugin-camera | @capacitor/camera | |
| cordova-plugin-geolocation | @capacitor/geolocation | |
| cordova-plugin-device | @capacitor/device | |
| cordova-plugin-network-information | @capacitor/network | |
| cordova-plugin-statusbar | @capacitor/status-bar | |
| cordova-plugin-splashscreen | @capacitor/splash-screen | |
| cordova-plugin-keyboard | @capacitor/keyboard | |
| cordova-plugin-dialogs | @capacitor/dialog | |
| cordova-plugin-file | @capacitor/filesystem | |
| cordova-plugin-inappbrowser | @capacitor/browser | |
| cordova-plugin-media | @capacitor/media | Custom or use @capgo plugins |
| cordova-plugin-vibration | @capacitor/haptics | |
| cordova-plugin-local-notifications | @capacitor/local-notifications | |
| cordova-plugin-push | @capacitor/push-notifications | |
| Cordova插件 | Capacitor替代插件 | 安装命令 |
|---|---|---|
| cordova-plugin-camera | @capacitor/camera | |
| cordova-plugin-geolocation | @capacitor/geolocation | |
| cordova-plugin-device | @capacitor/device | |
| cordova-plugin-network-information | @capacitor/network | |
| cordova-plugin-statusbar | @capacitor/status-bar | |
| cordova-plugin-splashscreen | @capacitor/splash-screen | |
| cordova-plugin-keyboard | @capacitor/keyboard | |
| cordova-plugin-dialogs | @capacitor/dialog | |
| cordova-plugin-file | @capacitor/filesystem | |
| cordova-plugin-inappbrowser | @capacitor/browser | |
| cordova-plugin-media | @capacitor/media | 自定义插件或使用Capgo插件 |
| cordova-plugin-vibration | @capacitor/haptics | |
| cordova-plugin-local-notifications | @capacitor/local-notifications | |
| cordova-plugin-push | @capacitor/push-notifications | |
Third-Party Cordova Plugins → Capgo Equivalents
第三方Cordova插件 → Capgo替代方案
For biometrics:
bash
undefined生物识别功能:
bash
undefinedCordova
Cordova版本
cordova plugin add cordova-plugin-fingerprint-aio
cordova plugin add cordova-plugin-fingerprint-aio
Capacitor
Capacitor版本
bun add @capgo/capacitor-native-biometric
**For payments:**
```bashbun add @capgo/capacitor-native-biometric
**支付功能:**
```bashCordova
Cordova版本
cordova plugin add cordova-plugin-purchase
cordova plugin add cordova-plugin-purchase
Capacitor
Capacitor版本
bun add @capgo/capacitor-purchases
**For social login:**
```bashbun add @capgo/capacitor-purchases
**社交登录:**
```bashFacebook登录
bun add @capgo/capacitor-social-login
bun add @capgo/capacitor-social-login
Google登录
bun add @codetrix-studio/capacitor-google-auth
**Check the full plugin catalog:**
https://github.com/Cap-go/awesome-capacitorbun add @codetrix-studio/capacitor-google-auth
**查看完整插件目录:**
https://github.com/Cap-go/awesome-capacitorStep 5: Update Code
步骤5:更新代码
Import Changes
导入方式变更
Cordova (old):
javascript
document.addEventListener('deviceready', () => {
navigator.camera.getPicture(success, error, options);
});Capacitor (new):
typescript
import { Camera } from '@capacitor/camera';
// No deviceready event needed
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});Cordova(旧版):
javascript
document.addEventListener('deviceready', () => {
navigator.camera.getPicture(success, error, options);
});Capacitor(新版):
typescript
import { Camera } from '@capacitor/camera';
// 无需等待deviceready事件
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Uri
});Common Pattern Changes
常见代码模式变更
Device Information:
typescript
// Cordova
const uuid = device.uuid;
const platform = device.platform;
// Capacitor
import { Device } from '@capacitor/device';
const info = await Device.getId();
const platform = await Device.getInfo();Network Status:
typescript
// Cordova
const networkState = navigator.connection.type;
// Capacitor
import { Network } from '@capacitor/network';
const status = await Network.getStatus();
console.log('Connected:', status.connected);Geolocation:
typescript
// Cordova
navigator.geolocation.getCurrentPosition(success, error);
// Capacitor
import { Geolocation } from '@capacitor/geolocation';
const position = await Geolocation.getCurrentPosition();设备信息获取:
typescript
// Cordova版本
const uuid = device.uuid;
const platform = device.platform;
// Capacitor版本
import { Device } from '@capacitor/device';
const info = await Device.getId();
const platform = await Device.getInfo();网络状态检测:
typescript
// Cordova版本
const networkState = navigator.connection.type;
// Capacitor版本
import { Network } from '@capacitor/network';
const status = await Network.getStatus();
console.log('已连接:', status.connected);地理位置获取:
typescript
// Cordova版本
navigator.geolocation.getCurrentPosition(success, error);
// Capacitor版本
import { Geolocation } from '@capacitor/geolocation';
const position = await Geolocation.getCurrentPosition();Remove deviceready Event
移除deviceready事件
Capacitor doesn't need deviceready. Plugins work immediately.
typescript
// Cordova (remove this)
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
// Your code
}
// Capacitor (just use directly)
import { Camera } from '@capacitor/camera';
async function takePicture() {
const photo = await Camera.getPhoto();
}Capacitor无需依赖deviceready事件,插件可直接使用。
typescript
// 移除Cordova的以下代码
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
// 你的代码
}
// Capacitor直接使用
import { Camera } from '@capacitor/camera';
async function takePicture() {
const photo = await Camera.getPhoto();
}Step 6: Update Configuration
步骤6:更新配置
Cordova uses config.xml. Capacitor uses capacitor.config.ts
Cordova使用config.xml,Capacitor使用capacitor.config.ts
Create capacitor.config.ts
创建capacitor.config.ts
typescript
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.company.app', // From config.xml widget id
appName: 'My App', // From config.xml name
webDir: 'www', // From Cordova build output
server: {
androidScheme: 'https'
},
plugins: {
SplashScreen: {
launchShowDuration: 3000,
backgroundColor: '#ffffff',
androidScaleType: 'CENTER_CROP',
showSpinner: false
}
}
};
export default config;typescript
import type { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.company.app', // 来自config.xml的widget id
appName: 'My App', // 来自config.xml的name
webDir: 'www', // 来自Cordova的构建输出目录
server: {
androidScheme: 'https'
},
plugins: {
SplashScreen: {
launchShowDuration: 3000,
backgroundColor: '#ffffff',
androidScaleType: 'CENTER_CROP',
showSpinner: false
}
}
};
export default config;Migrate config.xml Settings
迁移config.xml设置
Preferences:
xml
<!-- Cordova config.xml -->
<preference name="Orientation" value="portrait" />
<preference name="StatusBarOverlaysWebView" value="false" />
<preference name="StatusBarBackgroundColor" value="#000000" />Capacitor equivalent:
- Orientation: Set in Xcode/Android Studio per platform
- StatusBar: Use plugin
@capacitor/status-bar
Platform-specific config:
xml
<!-- Cordova config.xml -->
<platform name="ios">
<allow-intent href="itms:*" />
</platform>Capacitor equivalent:
typescript
// capacitor.config.ts
const config: CapacitorConfig = {
ios: {
contentInset: 'always',
},
android: {
allowMixedContent: true,
}
};偏好设置:
xml
<!-- Cordova config.xml -->
<preference name="Orientation" value="portrait" />
<preference name="StatusBarOverlaysWebView" value="false" />
<preference name="StatusBarBackgroundColor" value="#000000" />Capacitor等效配置:
- 屏幕方向:在Xcode/Android Studio中按平台单独设置
- 状态栏:使用插件
@capacitor/status-bar
平台专属配置:
xml
<!-- Cordova config.xml -->
<platform name="ios">
<allow-intent href="itms:*" />
</platform>Capacitor等效配置:
typescript
// capacitor.config.ts
const config: CapacitorConfig = {
ios: {
contentInset: 'always',
},
android: {
allowMixedContent: true,
}
};Step 7: Handle Permissions
步骤7:配置权限
Capacitor requires explicit permission configuration.
Capacitor需要显式配置权限。
iOS: Info.plist
iOS:Info.plist
Add to ios/App/App/Info.plist:
xml
<key>NSCameraUsageDescription</key>
<string>We need camera access to take photos</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need photo library access to select images</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need location to show nearby places</string>
<key>NSMicrophoneUsageDescription</key>
<string>We need microphone access for audio recording</string>添加到ios/App/App/Info.plist:
xml
<key>NSCameraUsageDescription</key>
<string>我们需要相机权限来拍摄照片</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>我们需要相册权限来选择图片</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>我们需要位置权限来展示附近地点</string>
<key>NSMicrophoneUsageDescription</key>
<string>我们需要麦克风权限来录制音频</string>Android: AndroidManifest.xml
Android:AndroidManifest.xml
Add to android/app/src/main/AndroidManifest.xml:
xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />添加到android/app/src/main/AndroidManifest.xml:
xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />Step 8: Sync and Build
步骤8:同步与构建
Sync web code with native projects:
bash
bunx cap syncThis copies:
- Web assets from to native projects
www/ - Installs native dependencies
- Updates plugin configurations
Build for iOS:
bash
bunx cap open ios同步Web代码到原生项目:
bash
bunx cap sync该命令会:
- 将中的Web资源复制到原生项目
www/ - 安装原生依赖
- 更新插件配置
构建iOS应用:
bash
bunx cap open iosThen build in Xcode (Cmd+R)
然后在Xcode中构建(Cmd+R)
**Build for Android:**
```bash
bunx cap open android
**构建Android应用:**
```bash
bunx cap open androidThen build in Android Studio (Run)
然后在Android Studio中构建(点击Run)
undefinedundefinedStep 9: Test the App
步骤9:测试应用
Test all plugin functionality:
- Camera/photo picker
- Geolocation
- File operations
- Network detection
- Device information
- Push notifications
Check for:
- Missing permissions
- API differences
- Callback → Promise conversions
- Removed plugins
测试所有插件功能:
- 相机/图片选择器
- 地理位置
- 文件操作
- 网络检测
- 设备信息
- 推送通知
检查以下内容:
- 缺失的权限
- API差异
- 回调转Promise的转换
- 已移除的插件
Step 10: Remove Cordova
步骤10:移除Cordova
Once migration is complete and tested:
bash
undefined迁移完成并测试通过后:
bash
undefinedRemove Cordova platforms
移除Cordova平台
cordova platform remove ios
cordova platform remove android
cordova platform remove ios
cordova platform remove android
Remove Cordova
移除Cordova核心依赖
bun remove cordova
bun remove cordova-ios
bun remove cordova-android
bun remove cordova
bun remove cordova-ios
bun remove cordova-android
Remove Cordova plugins
移除所有Cordova插件
cordova plugin list | xargs -I {} cordova plugin remove {}
cordova plugin list | xargs -I {} cordova plugin remove {}
Remove config.xml (after backing up)
备份后移除config.xml
mv config.xml config.xml.backup
undefinedmv config.xml config.xml.backup
undefinedCommon Issues and Solutions
常见问题与解决方案
Issue: Plugin Not Found
问题:插件未找到
Problem:
Error: Plugin not foundSolution:
- Check if plugin is installed:
bun list - Sync native projects:
bunx cap sync - Clean and rebuild in Xcode/Android Studio
报错信息:
Error: Plugin not found解决方案:
- 检查插件是否已安装:
bun list - 同步原生项目:
bunx cap sync - 在Xcode/Android Studio中清理并重新构建
Issue: deviceready Never Fires
问题:deviceready事件从未触发
Problem:
Cordova's deviceready event doesn't exist in Capacitor.
Solution:
Remove all event listeners. Capacitor plugins work immediately.
devicereadytypescript
// Remove this
document.addEventListener('deviceready', onDeviceReady);
// Use this
import { App } from '@capacitor/app';
App.addListener('appStateChange', (state) => {
console.log('App state changed:', state.isActive);
});问题描述:
Cordova的deviceready事件在Capacitor中不存在。
解决方案:
移除所有事件监听器,Capacitor插件可直接使用。
devicereadytypescript
// 移除以下代码
document.addEventListener('deviceready', onDeviceReady);
// 使用Capacitor的替代方案
import { App } from '@capacitor/app';
App.addListener('appStateChange', (state) => {
console.log('应用状态变更:', state.isActive);
});Issue: White Screen on Startup
问题:启动时显示白屏
Problem:
App shows white screen or crashes.
Solution:
- Check in capacitor.config.ts points to correct build output
webDir - Rebuild web app:
bun run build - Sync:
bunx cap sync - Check browser console in device for errors
问题描述:
应用启动时显示白屏或崩溃。
解决方案:
- 检查capacitor.config.ts中的是否指向正确的构建输出目录
webDir - 重新构建Web应用:
bun run build - 同步原生项目:
bunx cap sync - 在设备的浏览器控制台中查看错误信息
Issue: Permissions Not Working
问题:权限不生效
Problem:
Camera/location/etc. fail silently.
Solution:
- Add permission strings to Info.plist (iOS)
- Add permission declarations to AndroidManifest.xml (Android)
- Request permissions explicitly in code:
typescript
import { Camera } from '@capacitor/camera';
// Capacitor handles permission prompts automatically
const photo = await Camera.getPhoto();问题描述:
相机/位置等功能无响应。
解决方案:
- 在iOS的Info.plist中添加权限描述字符串
- 在Android的AndroidManifest.xml中添加权限声明
- 在代码中显式请求权限:
typescript
import { Camera } from '@capacitor/camera';
// Capacitor会自动处理权限请求弹窗
const photo = await Camera.getPhoto();Issue: Plugins Using Old Cordova API
问题:插件使用旧版Cordova API
Problem:
Some third-party Cordova plugins still reference Cordova global.
Solution:
Use the Capacitor Cordova compatibility layer:
bash
bun add cordova-plugin-example
bunx cap syncCapacitor includes Cordova compatibility, but:
- It's best to migrate to native Capacitor plugins when possible
- Not all Cordova plugins will work
问题描述:
部分第三方Cordova插件仍依赖Cordova全局对象。
解决方案:
使用Capacitor的Cordova兼容层:
bash
bun add cordova-plugin-example
bunx cap syncCapacitor内置Cordova兼容层,但注意:
- 尽可能迁移到原生Capacitor插件
- 并非所有Cordova插件都能正常工作
Hybrid Approach: Run Both
混合方案:同时运行两者
You can run Cordova and Capacitor side-by-side during migration.
- Install Capacitor alongside Cordova
- Keep both config.xml and capacitor.config.ts
- Migrate plugins incrementally
- Test each platform independently
When ready, remove Cordova entirely.
迁移过程中可同时运行Cordova和Capacitor:
- 在Cordova项目中安装Capacitor
- 同时保留config.xml和capacitor.config.ts
- 逐步迁移插件
- 独立测试每个平台
准备就绪后,再完全移除Cordova。
Plugin Migration Checklist
插件迁移检查清单
- List all Cordova plugins:
cordova plugin list - Find Capacitor equivalents (use table above)
- Install Capacitor plugins:
bun add @capacitor/plugin-name - Update imports in code
- Convert callbacks to async/await
- Remove event listeners
deviceready - Add permission strings (iOS Info.plist, Android AndroidManifest.xml)
- Sync native projects:
bunx cap sync - Test on physical devices
- Remove Cordova plugins after verification
- 列出所有Cordova插件:
cordova plugin list - 查找对应的Capacitor替代插件(参考上方表格)
- 安装Capacitor插件:
bun add @capacitor/plugin-name - 更新代码中的导入语句
- 将回调转换为async/await
- 移除事件监听器
deviceready - 添加权限描述字符串(iOS Info.plist、Android AndroidManifest.xml)
- 同步原生项目:
bunx cap sync - 在物理设备上测试
- 验证后移除Cordova插件
Live Updates with Capgo
使用Capgo实现实时更新
Capacitor enables instant updates without app store review.
After migration, add Capgo for OTA updates:
bash
undefinedCapacitor支持无需应用商店审核的即时更新。
迁移完成后,添加Capgo实现OTA更新:
bash
undefinedInstall Capgo plugin
安装Capgo插件
bun add @capgo/capacitor-updater
bun add @capgo/capacitor-updater
Create account at capgo.app
在capgo.app创建账户
bun add -g @capgo/cli
capgo login
bun add -g @capgo/cli
capgo login
Initialize and deploy
初始化并部署更新
capgo init
bun run build
capgo upload
Users get updates instantly. See the `capgo-live-updates` skill for details.capgo init
bun run build
capgo upload
用户可即时获取更新。详情请查看`capgo-live-updates`指南。Resources
参考资源
- Official Migration Guide: https://capacitorjs.com/docs/cordova/migrating-from-cordova-to-capacitor
- Capacitor Docs: https://capacitorjs.com/docs
- Plugin Search: https://github.com/Cap-go/awesome-capacitor
- Capgo Plugins: https://github.com/Cap-go?q=capacitor
- Community Forum: https://forum.ionicframework.com/c/capacitor
Migration Timeline Estimate
迁移时间预估
| App Size | Estimated Time |
|---|---|
| Small (1-3 plugins) | 2-4 hours |
| Medium (4-8 plugins) | 1-2 days |
| Large (9+ plugins) | 3-5 days |
| Enterprise (custom plugins) | 1-2 weeks |
| 应用规模 | 预估时间 |
|---|---|
| 小型(1-3个插件) | 2-4小时 |
| 中型(4-8个插件) | 1-2天 |
| 大型(9个以上插件) | 3-5天 |
| 企业级(含自定义插件) | 1-2周 |
Post-Migration Benefits
迁移后的优势
After migrating from Cordova to Capacitor:
✅ Faster development - Direct access to Xcode/Android Studio
✅ Live updates - Deploy updates without app store review (with Capgo)
✅ Better TypeScript - Full type safety
✅ Modern APIs - Promise-based, async/await
✅ Active maintenance - Regular updates and improvements
✅ Better debugging - Native IDE debugging tools
✅ Improved performance - Optimized native bridge
从Cordova迁移到Capacitor后,你将获得:
✅ 更快的开发效率 - 直接访问Xcode/Android Studio
✅ 实时更新 - 无需应用商店审核即可部署更新(搭配Capgo)
✅ 更完善的TypeScript支持 - 全面的类型安全
✅ 现代API风格 - Promise式、async/await语法
✅ 活跃的维护 - 定期更新与功能改进
✅ 更优的调试体验 - 原生IDE调试工具
✅ 性能提升 - 优化的原生桥接层
Next Steps
后续步骤
- Complete the migration using steps above
- Test thoroughly on physical devices
- Set up CI/CD (see skill)
capacitor-ci-cd - Add live updates (see skill)
capgo-live-updates - Submit to app stores (see skill)
capacitor-app-store
- 按照上述步骤完成迁移
- 在物理设备上全面测试
- 搭建CI/CD流程(查看指南)
capacitor-ci-cd - 添加实时更新功能(查看指南)
capgo-live-updates - 提交应用到应用商店(查看指南)
capacitor-app-store