配置系统 #
一、配置文件概述 #
1.1 配置文件类型 #
Capacitor支持两种配置文件格式:
| 格式 | 文件名 | 说明 |
|---|---|---|
| JSON | capacitor.config.json | 默认格式,简单易用 |
| TypeScript | capacitor.config.ts | 支持类型检查和动态配置 |
1.2 配置优先级 #
text
命令行参数 > 环境变量 > capacitor.config > 默认值
二、基础配置 #
2.1 JSON配置 #
json
{
"appId": "com.example.myapp",
"appName": "My App",
"webDir": "dist",
"bundledWebRuntime": false,
"server": {
"iosScheme": "https",
"androidScheme": "https"
}
}
2.2 TypeScript配置 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist',
bundledWebRuntime: false,
server: {
iosScheme: 'https',
androidScheme: 'https'
}
};
export default config;
2.3 动态配置 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
const isProduction = process.env.NODE_ENV === 'production';
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist',
server: isProduction ? undefined : {
url: 'http://localhost:5173',
iosScheme: 'https',
androidScheme: 'https',
cleartext: true
}
};
export default config;
三、核心配置项 #
3.1 应用标识配置 #
typescript
interface AppConfig {
// 应用包名(必需)
// 格式:反向域名,如 com.company.appname
appId: string;
// 应用显示名称(必需)
appName: string;
// Web构建输出目录(必需)
webDir: string;
// 是否打包Capacitor运行时
// 默认false,推荐使用npm安装
bundledWebRuntime?: boolean;
}
appId命名规范:
typescript
// 正确示例
"com.company.myapp"
"com.example.todoapp"
"io.github.username.project"
// 错误示例
"myapp" // 太短
"MyApp" // 包含大写
"com.my-app" // 包含连字符
3.2 服务器配置 #
typescript
interface ServerConfig {
// 开发服务器URL(仅开发时使用)
url?: string;
// iOS URL Scheme
iosScheme?: 'http' | 'https';
// Android URL Scheme
androidScheme?: 'http' | 'https';
// 是否允许HTTP明文传输(Android)
cleartext?: boolean;
// 主机名(覆盖默认)
hostname?: string;
// 端口号(覆盖默认)
port?: number;
// iOS背景运行
iosAllowsArbitraryLoads?: boolean;
// Android混合内容
androidAllowMixedContent?: boolean;
}
配置示例:
typescript
const config: CapacitorConfig = {
// ... 其他配置
// 生产环境
server: {
iosScheme: 'https',
androidScheme: 'https'
},
// 开发环境
// server: {
// url: 'http://192.168.1.100:5173',
// iosScheme: 'https',
// androidScheme: 'https',
// cleartext: true
// }
};
3.3 iOS配置 #
typescript
interface IOSConfig {
// 内容边距模式
contentInset?: 'automatic' | 'always' | 'never';
// 内容模式
preferredContentMode?: 'mobile' | 'desktop';
// 是否启用滚动
scrollEnabled?: boolean;
// 背景颜色
backgroundColor?: string;
// 允许任意加载
allowsArbitraryLoads?: boolean;
// 键盘显示调整
keyboardDisplayRequiresUserAction?: boolean;
// 允许链接预览
allowsLinkPreview?: boolean;
// 自定义scheme
scheme?: string;
// 自定义主机
hostname?: string;
}
配置示例:
typescript
const config: CapacitorConfig = {
ios: {
contentInset: 'automatic',
preferredContentMode: 'mobile',
scrollEnabled: true,
backgroundColor: '#ffffff',
allowsLinkPreview: false
}
};
3.4 Android配置 #
typescript
interface AndroidConfig {
// 允许混合内容
allowMixedContent?: boolean;
// 捕获输入
captureInput?: boolean;
// WebView调试
webContentsDebuggingEnabled?: boolean;
// 背景颜色
backgroundColor?: string;
// 自定义scheme
scheme?: string;
// 自定义主机
hostname?: string;
}
配置示例:
typescript
const config: CapacitorConfig = {
android: {
allowMixedContent: true,
captureInput: true,
webContentsDebuggingEnabled: !isProduction,
backgroundColor: '#ffffff'
}
};
四、插件配置 #
4.1 插件配置结构 #
typescript
interface PluginsConfig {
[pluginName: string]: {
[key: string]: any;
};
}
4.2 常用插件配置 #
typescript
const config: CapacitorConfig = {
// ... 其他配置
plugins: {
// 启动画面配置
SplashScreen: {
launchShowDuration: 2000,
backgroundColor: '#ffffff',
androidSplashResourceName: 'splash',
androidScaleType: 'CENTER_CROP',
showSpinner: false,
spinnerColor: '#4a90d9',
splashFullScreen: true,
splashImmersive: true
},
// 状态栏配置
StatusBar: {
style: 'DARK',
backgroundColor: '#4a90d9',
overlaysWebView: false
},
// 键盘配置
Keyboard: {
resize: 'body',
resizeOnFullScreen: true,
style: 'dark',
resizeMode: 'native'
},
// 相机配置
Camera: {
permissions: {
ios: ['camera', 'photos'],
android: ['camera', 'read_external_storage', 'write_external_storage']
}
},
// 地理位置配置
Geolocation: {
permissions: {
ios: ['location', 'locationWhenInUse'],
android: ['access_coarse_location', 'access_fine_location']
}
}
}
};
4.3 自定义插件配置 #
typescript
// 定义插件配置接口
interface MyPluginConfig {
apiKey: string;
environment: 'development' | 'production';
debugMode?: boolean;
}
// 在配置中使用
const config: CapacitorConfig = {
plugins: {
MyCustomPlugin: {
apiKey: process.env.MY_API_KEY || '',
environment: isProduction ? 'production' : 'development',
debugMode: !isProduction
} as MyPluginConfig
}
};
五、平台特定配置 #
5.1 条件配置 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
const isProduction = process.env.NODE_ENV === 'production';
const platform = process.env.CAPACITOR_PLATFORM;
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist',
// 根据平台配置
ios: platform === 'ios' ? {
backgroundColor: '#f5f5f5'
} : undefined,
android: platform === 'android' ? {
backgroundColor: '#f5f5f5'
} : undefined
};
export default config;
5.2 环境配置文件 #
text
config/
├── capacitor.config.base.ts # 基础配置
├── capacitor.config.dev.ts # 开发环境
├── capacitor.config.staging.ts # 测试环境
└── capacitor.config.prod.ts # 生产环境
typescript
// capacitor.config.base.ts
import { CapacitorConfig } from '@capacitor/cli';
export const baseConfig: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist'
};
// capacitor.config.prod.ts
import { CapacitorConfig } from '@capacitor/cli';
import { baseConfig } from './capacitor.config.base';
const config: CapacitorConfig = {
...baseConfig,
server: {
iosScheme: 'https',
androidScheme: 'https'
}
};
export default config;
六、原生项目配置 #
6.1 iOS配置 #
Info.plist配置 #
xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- 应用信息 -->
<key>CFBundleDisplayName</key>
<string>My App</string>
<key>CFBundleIdentifier</key>
<string>com.example.myapp</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<!-- 支持的界面方向 -->
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<!-- 状态栏 -->
<key>UIStatusBarHidden</key>
<false/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>
<!-- 权限描述 -->
<key>NSCameraUsageDescription</key>
<string>需要访问相机来拍照</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问相册来选择照片</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>需要获取您的位置信息</string>
<!-- 网络安全 -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
<!-- 后台模式 -->
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
<string>location</string>
</array>
</dict>
</plist>
通过Capacitor配置Info.plist #
typescript
const config: CapacitorConfig = {
ios: {
// 这会自动更新Info.plist
contentInset: 'automatic'
}
};
6.2 Android配置 #
AndroidManifest.xml配置 #
xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<!-- 权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle配置 #
groovy
android {
namespace "com.example.myapp"
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0.0"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
七、环境变量 #
7.1 使用环境变量 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = {
appId: process.env.APP_ID || 'com.example.myapp',
appName: process.env.APP_NAME || 'My App',
webDir: 'dist',
server: process.env.DEV_SERVER ? {
url: process.env.DEV_SERVER,
iosScheme: 'https',
androidScheme: 'https',
cleartext: true
} : undefined
};
export default config;
7.2 .env文件 #
bash
# .env
APP_ID=com.example.myapp
APP_NAME=My App
# .env.development
DEV_SERVER=http://192.168.1.100:5173
# .env.production
# 生产环境不需要DEV_SERVER
7.3 加载环境变量 #
typescript
// 使用dotenv加载
import { config as dotenvConfig } from 'dotenv';
import { CapacitorConfig } from '@capacitor/cli';
// 根据环境加载配置
const env = process.env.NODE_ENV || 'development';
dotenvConfig({ path: `.env.${env}` });
const config: CapacitorConfig = {
appId: process.env.APP_ID!,
appName: process.env.APP_NAME!,
webDir: 'dist'
};
export default config;
八、配置验证 #
8.1 类型检查 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
// TypeScript会自动进行类型检查
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist',
// 类型错误会被检测
// ios: {
// contentInset: 'invalid' // Error: Type '"invalid"' is not assignable
// }
};
8.2 运行时验证 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
function validateConfig(config: CapacitorConfig): void {
// 验证appId格式
if (!/^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/.test(config.appId)) {
throw new Error(`Invalid appId format: ${config.appId}`);
}
// 验证appName
if (!config.appName || config.appName.length === 0) {
throw new Error('appName is required');
}
// 验证webDir
if (!config.webDir) {
throw new Error('webDir is required');
}
}
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist'
};
validateConfig(config);
九、配置同步 #
9.1 同步流程 #
bash
# 同步配置到原生项目
npx cap sync
# 同步特定平台
npx cap sync ios
npx cap sync android
9.2 同步内容 #
text
capacitor.config.json
│
├──▶ ios/App/App/capacitor.config.json
│
└──▶ android/app/src/main/assets/capacitor.config.json
9.3 自动同步 #
json
// package.json
{
"scripts": {
"build": "vite build && npx cap sync",
"build:ios": "vite build && npx cap sync ios",
"build:android": "vite build && npx cap sync android"
}
}
十、配置最佳实践 #
10.1 配置分离 #
typescript
// config/app.config.ts
export const appConfig = {
id: 'com.example.myapp',
name: 'My App',
version: '1.0.0'
};
// config/server.config.ts
export const serverConfig = {
iosScheme: 'https' as const,
androidScheme: 'https' as const
};
// capacitor.config.ts
import { CapacitorConfig } from '@capacitor/cli';
import { appConfig } from './config/app.config';
import { serverConfig } from './config/server.config';
const config: CapacitorConfig = {
appId: appConfig.id,
appName: appConfig.name,
webDir: 'dist',
server: serverConfig
};
export default config;
10.2 环境区分 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
type Environment = 'development' | 'staging' | 'production';
const ENV: Environment = (process.env.NODE_ENV as Environment) || 'development';
const configs: Record<Environment, CapacitorConfig> = {
development: {
appId: 'com.example.myapp.dev',
appName: 'My App (Dev)',
webDir: 'dist',
server: {
url: 'http://localhost:5173',
iosScheme: 'https',
androidScheme: 'https',
cleartext: true
}
},
staging: {
appId: 'com.example.myapp.staging',
appName: 'My App (Staging)',
webDir: 'dist'
},
production: {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist'
}
};
export default configs[ENV];
10.3 敏感信息处理 #
typescript
import { CapacitorConfig } from '@capacitor/cli';
// 不要在配置中硬编码敏感信息
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'My App',
webDir: 'dist',
plugins: {
MyPlugin: {
// 从环境变量读取
apiKey: process.env.MY_API_KEY,
// 不要这样写
// apiKey: 'sk-xxxxx' // 错误!
}
}
};
export default config;
十一、总结 #
11.1 配置要点 #
| 配置项 | 必需 | 说明 |
|---|---|---|
| appId | 是 | 应用包名 |
| appName | 是 | 应用名称 |
| webDir | 是 | Web输出目录 |
| server | 否 | 服务器配置 |
| ios | 否 | iOS配置 |
| android | 否 | Android配置 |
| plugins | 否 | 插件配置 |
11.2 下一步 #
了解配置系统后,让我们学习 生命周期!
最后更新:2026-03-28