Memulai
-
Instal paket
Terminal window npm i @capgo/capacitor-envTerminal window pnpm add @capgo/capacitor-envTerminal window yarn add @capgo/capacitor-envTerminal window bun add @capgo/capacitor-env -
Sinkronkan platform native
Terminal window npx cap syncTerminal window pnpm cap syncTerminal window yarn cap syncTerminal window bunx cap sync
Deklarasikan nilai konfigurasi
Section titled “Deklarasikan nilai konfigurasi”Tambahkan kunci ke konfigurasi Capacitor agar tertanam ke dalam build native Anda. Anda dapat membuat beberapa varian konfigurasi (capacitor.config.prod.ts, capacitor.config.dev.ts, dll.) untuk menukar nilai per lingkungan.
import { CapacitorConfig } from '@capacitor/cli';
const config: CapacitorConfig = { appId: 'com.example.app', appName: 'Example', webDir: 'dist', plugins: { Env: { API_URL: 'https://api.example.com', PUBLIC_KEY: 'pk_live_123', }, },};
export default config;Pada platform native, nilai-nilai tersebut disimpan di dalam file konfigurasi yang dihasilkan (ios/App/App/capacitor.config.json dan android/app/src/main/assets/capacitor.config.json). Perbarui file-file tersebut per flavor jika Anda memerlukan nilai khusus tenant.
Baca nilai dalam kode
Section titled “Baca nilai dalam kode”import { Env } from '@capgo/capacitor-env';
const apiUrl = await Env.getKey({ key: 'API_URL' }).then((result) => result.value);
if (!apiUrl) { throw new Error('Missing API_URL configuration');}Sediakan fallback
Section titled “Sediakan fallback”const loadConfig = async () => { const { value: endpoint } = await Env.getKey({ key: 'API_URL' }); return endpoint || 'https://staging.example.com';};- Gunakan file
capacitor.configyang berbeda per lingkungan dan arahkan CLI ke file yang tepat dengannpx cap run ios --configuration=prod. - Gabungkan dengan channel updater Capgo untuk mengirim nilai khusus tenant tanpa menerbitkan binary baru.
- Jaga rahasia keluar dari source control dengan mengganti mereka selama build CI Anda sebelum
npx cap sync.