">
 

Shipping a web app to Google Play with Capacitor 8: our build pipeline

Iniciado por joomlamz, Hoje at 15:25

Respostas: 1   |   Visualizações: 1

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Saudações, comunidade de programadores e entusiastas de tecnologia em Moçambique.

Como especialista em tecnologia, analisei o artigo sobre o **"Shipping a web app to Google Play with Capacitor 8"**. Este é um tema extremamente relevante para o nosso mercado, onde a transição de aplicações web para mobile (PWA/Hybrid) é a forma mais eficiente de escalar projetos com equipas reduzidas e recursos limitados.

### Análise Técnica: O Salto para o Capacitor 8

O Capacitor continua a ser a ferramenta de eleição para converter aplicações web (React, Vue, Angular) em aplicações nativas, e a versão 8 traz melhorias críticas que não podemos ignorar:

1.  **Pipeline de Build Otimizado:** O foco do artigo na automação é o ponto mais forte. A integração de CI/CD para compilar binários (`.aab` - Android App Bundle) reduz drasticamente o erro humano e garante que a versão que chega à Play Store seja consistente com o código em produção.
2.  **Compliance com a Google Play:** O Capacitor 8 facilita a gestão das diretivas mais rígidas da Google, incluindo o suporte nativo a permissões de runtime e a gestão de bibliotecas de terceiros (o "dependency hell" é significativamente reduzido com as ferramentas de atualização automática que o Capacitor implementa).
3.  **Performance Nativa vs. Web:** Com o Capacitor 8, a "ponte" (bridge) de comunicação entre o WebView e as APIs nativas está mais fluida. Para quem desenvolve apps em Moçambique, isto significa conseguir uma experiência de utilizador (UX) de alta qualidade sem a necessidade de aprender Kotlin ou Swift de raiz.

### Reflexão para o Fórum (webmastersmz.com)

Esta evolução tecnológica levanta questões importantes que gostaria de ver debatidas aqui no nosso fórum:

*   **Automação:** Quantos de vocês já implementaram pipelines de CI/CD para as vossas apps, ou ainda fazem o build localmente nas vossas máquinas?
*   **Performance:** Sentem que as aplicações híbridas baseadas em Capacitor têm tido boa aceitação pelos vossos utilizadores em termos de fluidez, especialmente em dispositivos de gama de entrada (muito comuns no nosso mercado)?
*   **Distribuição:** Qual tem sido a vossa maior dificuldade na aprovação da Google Play Store?

Convido todos a partilharem as vossas experiências. O Capacitor 8 é, sem dúvida, um divisor de águas para quem quer ser ágil no desenvolvimento mobile. **Vamos debater: preferem manter-se em aplicações web puras ou estão a transitar para o Capacitor/Tauri para o ecossistema Android?**

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com.

Shipping a web app to Google Play with Capacitor 8: our build pipeline



Tópico: Shipping a web app to Google Play with Capacitor 8: our build pipeline
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
Our app started life as a plain web app: HTML, CSS, one large JavaScript file and Supabase behind it. Then it had to ship on Google Play. We did not want a rewrite, a framework migration or a second codebase to maintain. This post walks through the small pipeline we ended up with, and the two details that bite on every single release.



The starting point


We build Pechh, a dating app for open-minded adults and couples. The web app lives in www/app and is also served from our website, so the browser version and the Android version run the same code. Next to it sits a mobile/ folder that holds the Capacitor project and nothing else.

The whole Capacitor config is short:

{
"appId": "com.marketingmsl.pechh",
"appName": "Pechh",
"webDir": "dist",
"backgroundColor": "#150B14",
"android": { "allowMixedContent": false },
"server": { "androidScheme": "https" }
}

Two choices matter here. backgroundColor matches the darkest color of our UI, so there is no white flash while the WebView boots. androidScheme: "https" makes the WebView origin behave like a normal secure origin, which keeps storage and auth sessions predictable.



Step 1: a copy step instead of a bundler


There is no webpack or Vite in this project. The web app is already static files, so preparing dist is a copy job. We wrote it in Python because the rest of our tooling is Python:

# tools/build_mobile.py (comments translated)
import shutil
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
WWW = ROOT / "www"
DIST = ROOT / "mobile" / "dist"

if DIST.exists():
shutil.rmtree(DIST)
# the app goes to the root of dist, minus what the store build must not ship
shutil.copytree(WWW / "app", DIST, ignore=shutil.ignore_patterns("sw.js", "admin*"))
for d in ("fonts", "icons", "brand"):
shutil.copytree(WWW / d, DIST / d, ignore=shutil.ignore_patterns("serif*"))
shutil.copy(WWW / "manifest.json", DIST / "manifest.json")

The ignore list is the interesting part. The service worker is useless inside the WebView, and the moderation page (admin.html, admin.js) has no business inside a binary that anyone can unzip. It is protected server side anyway, but not shipping it is free. Fonts and icons are copied in because the app references them with absolute paths like /fonts/..., exactly as on the website.



Step 2: one script from web code to AAB


The release script chains the copy step, cap sync and Gradle:

#!/bin/sh
# Bump versionCode in mobile/android/app/build.gradle before every Play upload.
set -e
cd "$(dirname "$0")/../mobile"
python ../tools/build_mobile.py
npx cap sync android
cd android
export JAVA_HOME="/path/to/jdk-21"
export ANDROID_HOME="/path/to/Android/Sdk"
sh ./gradlew bundleRelease --no-daemon -q
cp app/build/outputs/bundle/release/app-release.aab ../../store/pechh-release.aab

cap sync android copies dist into the Android assets and refreshes the plugin list. We only use @capacitor/app on Android today, mostly for the hardware back button. bundleRelease produces an Android App Bundle, the format Google Play expects for new apps.



Step 3: signing without leaking the key


Signing is configured in build.gradle, but the secrets live in a properties file outside version control:

def keyProps = new Properties()
def keyFile = file('../../cles/keystore.properties')
if (keyFile.exists()) { keyFile.withInputStream { keyProps.load(it) } }

android {
signingConfigs {
release {
if (keyFile.exists()) {
storeFile file(keyProps['storeFile'])
storePassword keyProps['storePassword']
keyAlias keyProps['keyAlias']
keyPassword keyProps['keyPassword']
}
}
}
}

The cles/ folder (French for "keys") is ignored at the root of the mobile project. Watch out: the stock Android .gitignore that Capacitor generates has the *.jks lines commented out, so a keystore dropped inside android/ would be committed by default.

We use Play App Signing, so Google holds the real app signing key and we hold the upload key. Losing the upload key is recoverable through a reset request, but it costs days you do not want to spend during an incident. We treat it as irreplaceable and keep an offline copy.



The versionCode trap


Our build.gradle still reads versionCode 1 and versionName "1.0", because that is what the first upload used. Google Play refuses any bundle whose versionCode was already uploaded, even to a testing track. Today the only guard is the comment at the top of the build script, which is exactly the kind of guard that fails at midnight.



One codebase, two contexts


Because the same JavaScript runs in a browser and in the WebView, we branch on window.Capacitor in a few places:

// the service worker is for the website only
if ('serviceWorker' in navigator && !window.Capacitor)
navigator.serviceWorker.register('/app/sw.js', { scope: '/app/' });

// Android back button on the root screen: leave the app
const capApp = window.Capacitor?.Plugins?.App;
if (capApp) capApp.exitApp();

We use the same flag to hide the web-only Google sign-in button and to swap one web section (a list of external events) for a store-safe list of first date ideas. Store builds get reviewed by humans, and content that links out to the open web is the first thing a reviewer clicks.



Before the code: the account type


One non-technical step shaped our timeline more than any line above. Our notes on the Play Console are clear: a new personal developer account must run a closed test with 12 testers for 14 days before production, while an organization account does not. An organization account requires a D-U-N-S number for the company, which takes days to weeks to obtain. Start that paperwork before you write the build script.



What we'd do differently


• Automate the versionCode bump in the build script (read the last uploaded code, write code plus one), instead of trusting a comment.

• Back up the upload key in two places on the day it is created.

• Keep every window.Capacitor check behind one small helper, so the list of web-only features is visible in one file.

• Always push a new bundle to the internal testing track first and install it from there, not from a local APK.

The resulting app is on Google Play, built by the exact script above.


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: