📱 JavaScript - Partie 10

Mobile & Desktop Apps : React Native, Electron, Capacitor, PWA

🚀 Multiplateforme & Cross-platform
0%

1. Solutions Multiplatformes Overview

Créez des apps iOS, Android, Desktop, Web avec une seule base de code.

⚛️
React Native

Apps mobiles natives (iOS/Android) avec React

Meta 2015
Electron

Apps desktop (Windows/Mac/Linux) avec web technologies

GitHub 2013
🔌
Capacitor / Cordova

Web apps → Mobile hybride

Ionic 2017
🌐
PWA

Installable, offline, notifications

Google 2015

2. React Native - Apps Mobiles Natives React Native

Développez pour iOS et Android avec React.

// App React Native import React, { useState } from 'react'; import { View, Text, TouchableOpacity, StyleSheet, FlatList } from 'react-native'; const App = () => { const [count, setCount] = useState(0); const [items, setItems] = useState([]); return ( React Native App Compteur: {count} setCount(count + 1)}> Incrémenter {item}} keyExtractor={(item, idx) => idx.toString()} /> ); }; // Navigation import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack'; const Stack = createNativeStackNavigator(); function MyStack() { return ( ); } // Accès natif - API Camera import { launchCamera } from 'react-native-image-picker'; const openCamera = () => { launchCamera({ mediaType: 'photo' }, (response) => { if (response.assets) { setPhoto(response.assets[0].uri); } }); };
📱 Simulation React Native - Todo Mobile

📱 Todo App

0

3. Electron - Applications Desktop Electron

VS Code, Slack, Discord, Spotify - tous développés avec Electron.

// main.js (Process principal) const { app, BrowserWindow, ipcMain, Menu } = require('electron'); const path = require('path'); function createWindow() { const win = new BrowserWindow({ width: 1200, height: 800, webPreferences: { nodeIntegration: true, contextIsolation: false, preload: path.join(__dirname, 'preload.js') } }); win.loadFile('index.html'); win.webContents.openDevTools(); // DevTools } // Menu personnalisé const template = [ { label: 'Fichier', submenu: [ { label: 'Nouveau', accelerator: 'CmdOrCtrl+N', click: () => createNewFile() }, { type: 'separator' }, { label: 'Quitter', accelerator: 'CmdOrCtrl+Q', role: 'quit' } ]}, { label: 'Édition', submenu: [ { label: 'Copier', accelerator: 'CmdOrCtrl+C', role: 'copy' }, { label: 'Coller', accelerator: 'CmdOrCtrl+V', role: 'paste' } ]} ]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); // Communication IPC (main <-> renderer) ipcMain.handle('get-user-data', async (event, arg) => { return { name: 'User', id: 123 }; }); // Notification système new Notification({ title: 'Desktop App', body: 'Message depuis l\'application!' }).show(); // Tray (icône barre d'état) const Tray = require('electron').Tray; const tray = new Tray('icon.png'); tray.setToolTip('Mon App');
💻 Simulation Desktop App (Electron)
My Electron App

🚀 Application Desktop

Compteur: 0

4. PWA - Progressive Web Apps PWA

Applications web qui s'installent et fonctionnent hors ligne.

// manifest.json - Configuration PWA { "name": "Mon App Progressive", "short_name": "MonApp", "start_url": "/", "display": "standalone", "theme_color": "#34e89e", "background_color": "#ffffff", "icons": [ { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } ] } // Service Worker - Cache hors ligne const CACHE_NAME = 'my-pwa-cache-v1'; const urlsToCache = ['/', '/index.html', '/style.css', '/app.js']; self.addEventListener('install', event => { event.waitUntil( caches.open(CACHE_NAME).then(cache => cache.addAll(urlsToCache)) ); }); self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request).then(response => { return response || fetch(event.request); }) ); }); // Installation de la PWA if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js'); } // Prompt d'installation let deferredPrompt; window.addEventListener('beforeinstallprompt', (e) => { deferredPrompt = e; // Afficher un bouton "Installer" });
📱 PWA - Installable & Offline

✅ PWA prête à être installée sur votre appareil !

5. Capacitor & Ionic - Bridge Web/Natif Capacitor

Transformez votre app web en application mobile native.

// Capacitor - Accès natif depuis le web import { Capacitor } from '@capacitor/core'; import { Camera, CameraResultType } from '@capacitor/camera'; import { Geolocation } from '@capacitor/geolocation'; import { Share } from '@capacitor/share'; import { Preferences } from '@capacitor/preferences'; // Prendre une photo async function takePhoto() { const image = await Camera.getPhoto({ quality: 90, allowEditing: true, resultType: CameraResultType.Uri }); return image.webPath; } // Géolocalisation async function getPosition() { const coordinates = await Geolocation.getCurrentPosition(); return coordinates; } // Partage async function shareText(text) { await Share.share({ title: 'Partage', text: text }); } // Stockage natif await Preferences.set({ key: 'user', value: JSON.stringify(userData) }); const data = await Preferences.get({ key: 'user' }); // Ionic - UI Components import { IonContent, IonHeader, IonTitle, IonToolbar, IonButton, IonList, IonItem } from '@ionic/react';
🔌 Simulation Capacitor - Bridge Web/Natif

6. Comparaison des Solutions Comparison

Quand choisir quelle technologie ?

Critère React Native Flutter Native (iOS/Android) PWA
Performance⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
Productivité⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
Communauté⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️⭐️
App Store/Play Store
Accès natifBridgePlatform ChannelsDirectPlugin
Hot Reload✅ Oui✅ Oui✅ Oui✅ Oui
🎯 Recommandation personnalisée

7. Expo - Framework React Native Expo

Développement React Native accéléré avec Expo.

// Installation Expo // npx create-expo-app my-app // cd my-app // npm start // App avec Expo import { StatusBar } from 'expo-status-bar'; import { useFonts } from 'expo-font'; import * as ImagePicker from 'expo-image-picker'; import * as Location from 'expo-location'; export default function App() { const [fontsLoaded] = useFonts({ 'Inter-Bold': require('./assets/fonts/Inter-Bold.ttf'), }); // Demander permissions const [location, requestLocation] = Location.useForegroundPermissions(); // Expo Router (fichier-based routing) // app/index.tsx → /, app/about.tsx → /about return ( Expo App
⚡ Expo - Build & Deploy

8. État Global Cross-platform State

Partagez la logique entre web, mobile et desktop.

// Zustand (web, mobile, desktop) import { create } from 'zustand'; const useStore = create((set) => ({ user: null, theme: 'light', setUser: (user) => set({ user }), toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })) })); // Utilisation identique partout function Profile() { const { user, setUser } = useStore(); }
// Redux Toolkit (universel) import { configureStore, createSlice } from '@reduxjs/toolkit'; const appSlice = createSlice({ name: 'app', initialState: { offline: false, notifications: [] }, reducers: { setOffline: (state, action) => { state.offline = action.payload; } } }); // Fonctions pures partagées export const isValidEmail = (email) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); // Services partagés class ApiService { async fetchUsers() { return fetch('/api/users'); } }
🔄 Partage de logique multi-plateforme

9. Mini-projet : Notes App Cross-platform Project

Même app qui tourne sur Web, Mobile (React Native) et Desktop (Electron).

📝 Notes App - Multiplateforme

10. Déploiement sur Stores Store

Mettez vos apps sur App Store et Google Play.

# Google Play Store # 1. Générer APK/AAB cd android && ./gradlew bundleRelease # 2. Signer l'application jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 \ -keystore my-release-key.keystore app-release.aab alias_name # 3. Upload sur Google Play Console # Apple App Store # 1. Build iOS npx expo run:ios --configuration Release # 2. Archive dans Xcode # Product > Archive # 3. Upload sur App Store Connect # Transporter ou xcodebuild # Electron - Build pour distribution npm run make # Génère .exe (Windows), .dmg (Mac), .deb (Linux)
📦 Simulation Déploiement

🏆 Compétences acquises - Mobile & Desktop

✅ React Native (iOS & Android)
✅ Electron (Windows, Mac, Linux)
✅ PWA (Installable, offline)
✅ Capacitor / Ionic (Bridge)
✅ Expo (Accélération RN)
✅ État global cross-platform
✅ Déploiement stores
✅ API natives (camera, geoloc, notifs)

📚 Projets concrets à réaliser :

  • 📱 Application de notes → Electron (desktop) + PWA (web) + React Native (mobile)
  • 💻 Email client → Electron avec intégration IMAP
  • 📸 App photo → React Native + Capacitor pour accès caméra
  • 🎮 Jeu multiplateforme → PWA + React Native
  • 📊 Dashboard analytics → Electron + PWA
💡 Conseils pour le marché :
• React Native est le plus demandé pour le mobile (75% des offres)
• Electron pour les apps desktop d'entreprise (Slack, VS Code, Discord)
• PWA parfait pour les applications web "installables"
• Un développeur cross-platform est très recherché !