From faa96e657621455284245018b8a3b5050b613e6b Mon Sep 17 00:00:00 2001 From: julieng Date: Sun, 14 Nov 2021 14:30:47 +0100 Subject: convert content to md --- .../client-side_javascript_frameworks/index.md | 300 +++--- .../introduction/index.md | 459 ++++----- .../main_features/index.md | 457 +++++---- .../react_getting_started/index.md | 606 ++++++------ .../react_todo_list_beginning/index.md | 511 +++++----- .../vue_getting_started/index.md | 451 +++++---- .../cross_browser_testing/accessibility/index.md | 1029 ++++++++++---------- .../cross_browser_testing/html_and_css/index.md | 581 ++++++----- .../cross_browser_testing/index.md | 44 +- .../cross_browser_testing/introduction/index.md | 238 +++-- .../cross_browser_testing/javascript/index.md | 597 ++++++------ .../testing_strategies/index.md | 433 ++++---- files/fr/learn/tools_and_testing/github/index.md | 108 +- files/fr/learn/tools_and_testing/index.md | 30 +- .../command_line/index.md | 562 +++++------ .../understanding_client-side_tools/index.md | 32 +- 16 files changed, 3178 insertions(+), 3260 deletions(-) (limited to 'files/fr/learn/tools_and_testing') diff --git a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/index.md b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/index.md index fd3e443982..7ffca23234 100644 --- a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/index.md +++ b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/index.md @@ -10,166 +10,144 @@ tags: - client-side translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks --- -
{{LearnSidebar}}
+{{LearnSidebar}} + +Les frameworks JavaScript sont une partie essentielle du développement web front-end moderne, fournissant aux développeurs des outils éprouvés pour construire des applications web évolutives et interactives. De nombreuses entreprises modernes utilisent des frameworks comme un élément normé de leur outillage, de sorte que de nombreux emplois de développement front-end requièrent désormais une expérience avec ces frameworks. + +En tant que futur développeur front-end, il peut être difficile de savoir par où commencer lors de l'apprentissage des frameworks – il y a tant de frameworks si différents les uns des autres et de nouveaux qui apparaissent sans cesse, ils fonctionnent généralement de manière similaire mais font certaines choses différemment, et il y a certaines choses spécifiques à avoir en tête lors de leur utilisation. + +Dans cet ensemble d'articles, nous chercherons à vous donner un point de départ confortable pour vous aider à commencer votre apprentissage des frameworks. Nous ne visons pas à vous enseigner exhaustivement tout ce que vous devez savoir sur React / ReactDOM, Vue ou quelque autre framework particulier ; les documentations fournises par les équipes de développement des frameworks font déjà ce travail. Nous souhaitons plutôt faire simple et répondre d'abord à des questions plus fondamentales telles que : + +- Pourquoi devrais-je utiliser un framework ? Quels problèmes résolvent-ils pour moi ? +- Quelles questions devrais-je me poser pour choisir un framework ? Ai-je au moins besoin d'un framework ? +- Quelles fonctionnalités proposent les frameworks ? Comment fonctionnent-ils en général et comment diffèrent leurs  implantations de ces fonctionnalités ? +- Comment se rapportent-ils au JavaScript "vanilla" ou à l'HTML ? -

Les frameworks JavaScript sont une partie essentielle du développement web front-end moderne, fournissant aux développeurs des outils éprouvés pour construire des applications web évolutives et interactives. De nombreuses entreprises modernes utilisent des frameworks comme un élément normé de leur outillage, de sorte que de nombreux emplois de développement front-end requièrent désormais une expérience avec ces frameworks.

+Après ceci, nous vous fournirons quelques tutoriels couvrant les notions fondamentales de certains des principaux frameworks afin de vous fournir suffisamment de contexte et de familiarité pour commencer à approfondir par vous-même. Nous voulons que vous puissiez progresser et en apprendre plus sur les frameworks de manière pragmatique sans oublier les bonnes pratiques fondamentales du web telles que l'accessibilité. -

En tant que futur développeur front-end, il peut être difficile de savoir par où commencer lors de l'apprentissage des frameworks – il y a tant de frameworks si différents les uns des autres et de nouveaux qui apparaissent sans cesse, ils fonctionnent généralement de manière similaire mais font certaines choses différemment, et il y a certaines choses spécifiques à avoir en tête lors de leur utilisation.

- -

Dans cet ensemble d'articles, nous chercherons à vous donner un point de départ confortable pour vous aider à commencer votre apprentissage des frameworks. Nous ne visons pas à vous enseigner exhaustivement tout ce que vous devez savoir sur React / ReactDOM, Vue ou quelque autre framework particulier ; les documentations fournises par les équipes de développement des frameworks font déjà ce travail. Nous souhaitons plutôt faire simple et répondre d'abord à des questions plus fondamentales telles que :

- - - -

Après ceci, nous vous fournirons quelques tutoriels couvrant les notions fondamentales de certains des principaux frameworks afin de vous fournir suffisamment de contexte et de familiarité pour commencer à approfondir par vous-même. Nous voulons que vous puissiez progresser et en apprendre plus sur les frameworks de manière pragmatique sans oublier les bonnes pratiques fondamentales du web telles que l'accessibilité.

- -

Commencez dès maintenant, avec "Introduction aux frameworks côté client"

- -

Prérequis

- -

Vous devez vraiment connaitre les bases des principaux langages du web (HTML, CSS, et particulièrement JavaScript) avant d'essayer de vous lancer dans l'apprentissage des frameworks côté client.

- -

Votre code n'en sera que plus qualitatif et plus professionnel, et vous serez en mesure de résoudre vos problèmes avec plus de confiance si vous comprenez les fonctionnalités fondamentales du web sur lesquelles les frameworks s'appuient.

- -

Vous voulez devenir développeur web front-end ?

- -

Nous avons créé un cours qui inclut toutes les informations essentielles dont vous avez besoin pour atteindre votre objectif.

- -

Commencer

- -

Guides d'introduction

- -
-
1. Introduction aux frameworks côté client
-
Nous commençons notre aperçu des frameworks par un tour d'horizon général du domaine, notamment en regardant un bref historique de JavaScript et des frameworks, la raison pour laquelle les frameworks existent et ce qu'ils nous proposent, comment commencer à réfléchir au choix d'un framework à apprendre et quelles alternatives il y a aux frameworks côté client.
-
2. Principales caractéristiques du Framework
-
Chaque framework JavaScript majeur a une approche différente de la mise à jour du DOM, de la gestion des évènements du navigateur et de la manière dont rendre l'expérience de développement agréable. Cet article explorera les principales caractéristiques des 4 grands frameworks, en examinant comment les frameworks ont tendance à fonctionner à un haut niveau et les différences entre eux.
-
- -

Tutoriels sur React

- -
-

Note : Les tutoriels sur React ont été essayés pour la dernière fois en mai 2020, avec React/ReactDOM 16.13.1 et create-react-app 3.4.1.

- -

Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version finale de l'exemple de code d'application React dans notre todo-react repository. Pour une version exécutable en direct, voir https://mdn.github.io/todo-react-build/.

-
- -
-
1. Premier pas avec React
-
Dans cet article, nous dirons bonjour à React. Nous découvrirons les prémices de son fonctionnement et de ses cas d'utilisation, configurerons une chaine d'outils React de base sur notre ordinateur local et créerons et jouerons avec une application de démarrage simple, en apprenant un peu plus sur le fonctionnement de React dans le processus.
-
2. Début de notre liste de tâches React
-
Supposons que nous ayons été chargés de créer une preuve de concept dans React – une application qui permet aux utilisateurs d'ajouter, de modifier et de supprimer les tâches sur lesquelles ils souhaitent travailler, ainsi que de marquer les tâches comme terminées sans les supprimer. Cet article vous guidera tout au long de la mise en place de la structure et du style des composants de base de l'application, prêts pour la définition et l'interactivité des composants individuels, que nous ajouterons plus tard.
-
3. Diviser notre application React en composants
-
À ce stade, notre application est un monolithe. Avant de pouvoir lui faire faire des choses, nous devons le diviser en composants descriptifs gérables. React n'a pas de règles strictes pour ce qui est et n'est pas un composant - c'est à vous de décider ! Dans cet article, nous allons vous montrer un moyen judicieux de diviser notre application en composants.
-
4. Interactivité de React: évènements et états
-
Une fois notre plan de composants élaboré, il est maintenant temps de commencer à faire évoluer notre application d'une interface utilisateur complètement statique vers une interface qui nous permet réellement d'interagir et de modifier des choses. Dans cet article, nous allons le faire, en explorant les évènements et les états en cours de route.
-
5. Interactivité de React: modification, filtrage, rendu conditionné
-
Alors que nous approchons de la fin de notre voyage React (pour l'instant du moins), nous ajouterons la touche finale aux principaux domaines de fonctionnalités de notre application de liste de tâches. Cela comprend la possibilité de modifier les tâches existantes et de filtrer la liste des tâches entre toutes les tâches, terminées et incomplètes. Nous examinerons le rendu conditionné de l'interface utilisateur en cours de route.
-
6. Accessibilité dans React
-
Dans notre avant-dernier article du tutoriel, nous nous concentrerons sur l'accessibilité, y compris la gestion de la mise au point dans React, ce qui peut améliorer la convivialité et réduire la confusion pour les utilisateurs de clavier uniquement et de lecteur d'écran.
-
7. Ressources sur React
-
Notre dernier article vous fournit une liste de ressources sur React que vous pouvez utiliser pour aller plus loin dans votre apprentissage.
-
- -

Tutoriels sur Ember

- -
-

Note : Les tutoriels Ember ont été essayés pour la dernière fois en Mai 2020, avec Ember/Ember CLI version 3.18.0.

- -

Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version finale de l'exemple de code d'application Ember dans le Ember app code in the ember-todomvc-tutorial repository. Pour une version exécutable en direct, voir https://nullvoxpopuli.github.io/ember-todomvc-tutorial/ (cela inclut également quelques fonctionnalités supplémentaires non couvertes dans le tutoriel).

-
- -
-
1. Premiers pas avec Ember
-
Dans notre premier article sur Ember, nous verrons comment fonctionne Ember et ce à quoi il sert, installerons la chaine d'outils d'Ember localement, créerons un exemple d'application, puis effectuerons une configuration initiale pour la préparer au développement.
-
2. Structure et composant de l'application Ember
-
Dans cet article, nous commencerons à planifier la structure de notre application TodoMVC Ember, à ajouter du code HTML correspondant, puis nous diviserons cette structure HTML en composants.
-
3. Interactivité Ember : évènements, classes et états
-
À ce stade, nous allons commencer à ajouter de l'interactivité à notre application, offrant la possibilité d'ajouter et d'afficher de nouveaux éléments à notre liste. En cours de route, nous examinerons l'utilisation d'évènements dans Ember, la création de classes de composants pour contenir du code JavaScript pour contrôler les fonctionnalités interactives et la configuration d'un service pour suivre l'état des données de notre application.
-
4. Interactivité Ember : fonctionnalité du Footer, rendu conditionné
-
Il est maintenant temps de commencer à aborder la fonctionnalité de footer dans notre application. Ici, nous allons mettre à jour le compteur de tâches pour afficher le nombre correct de tâches à compléter et appliquer correctement le style aux tâches terminées (c'est-à-dire là dont la case a été cochée). Nous allons également câbler notre bouton "Effacer terminé". En cours de route, nous découvrirons comment utiliser le rendu conditionné dans nos modèles.
-
5. Routage dans Ember
-
Dans cet article, nous apprendrons les bases du routage avec Ember. Nous l'utiliserons pour fournir une URL unique pour chacune des trois vues à faire : "Tous", "Actif", et "Terminé".
-
6. Ressources sur Ember et dépannage
-
Notre dernier article sur Ember vous fournit une liste de ressources que vous pouvez utiliser pour aller plus loin dans votre apprentissage, ainsi que des dépannages utiles et d'autres informations.
-
- -

Tutoriels sur Vue

- -
-

Note : Les tutoriels sur Vue ont été essayés pour la dernière fois en mai 2020, avec Vue 2.6.11.

- -

Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version terminée de l'exemple de code d'application Vue dans notre todo-vue repository. Pour une version exécutable en direct, voir https://mdn.github.io/todo-vue/dist/.

-
- -
-
1. Premiers pas avec Vue
-
Maintenant, introduisons Vue, le troisième de nos frameworks. Dans cet article, nous allons examiner un peu le contexte de Vue, apprendre à l'installer et créer un nouveau projet, étudier la structure de haut niveau de l'ensemble du projet et d'un composant individuel, voir comment exécuter le projet localement, et préparez-le à commencer à construire notre exemple.
-
2. Création de notre premier composant Vue
-
Il est maintenant temps de plonger plus profondément dans Vue et de créer notre propre composant personnalisé (nous commencerons par créer un composant pour représenter chaque élément de la liste de tâches). En cours de route, nous découvrirons quelques concepts importants tels que l'appel de composants à l'intérieur d'autres composants, leur transmission de données via des accessoires et l'enregistrement de l'état des données.
-
3. Rendu d'une liste de composants Vue
-
À ce stade, nous avons un composant entièrement fonctionnel ; nous sommes maintenant prêts à ajouter plusieurs composants ToDoItem à notre application. Dans cet article, nous examinerons l'ajout d'un ensemble de données d'élément todo à notre composant App.vue que nous allons ensuite parcourir et afficher à l'intérieur des composants ToDoItem à l'aide de la directive v-for.
-
4. Ajout d'un nouveau formulaire todo: évènements, méthodes, et modèles Vue
-
Nous avons maintenant des exemples de données en place et une boucle qui prend chaque bit de données et le rend dans un ToDoItem dans notre application. Ce dont nous avons vraiment besoin ensuite, c'est la possibilité de permettre à nos utilisateurs de saisir leurs propres éléments à faire dans l'application, et pour cela, nous aurons besoin d'un texte <input>, un évènement à déclencher lorsque les données sont soumises, une méthode de déclenchement lors de la soumission pour ajouter les données et relancer la liste, et un modèle pour contrôler les données. C'est ce que nous allons couvrir dans cet article.
-
5. Styliser les composants Vue avec CSS
-
Le moment est enfin venu de rendre notre application un peu plus jolie. Dans cet article, nous explorerons les différentes façons de styliser les composants Vue avec CSS.
-
6. Utilisation des propriétés calculées de Vue
-
Dans cet article, nous allons ajouter un compteur qui affiche le nombre d'éléments à faire terminés, en utilisant une fonctionnalité de Vue appelée propriétés calculées. Celles-ci fonctionnent de la même manière que les méthodes, mais ne sont réexécutées que lorsque l'une de leurs dépendances change.
-
7. Rendu conditionnel Vue : éditer les todos existants
-
Il est maintenant temps d'ajouter l'un des éléments majeurs de la fonctionnalité qui nous manque toujours: la possibilité de modifier les éléments todos existants. Pour ce faire, nous profiterons des capacités de rendu conditionnel de Vue — à savoir v-if et v-else — pour nous permettre de basculer entre la vue d'élément todo existante et une vue d'édition où vous pouvez mettre à jour les étiquettes d'élément todo. Nous examinerons également l'ajout de fonctionnalités pour supprimer les éléments todo.
-
8. Gestion de la mise au poinr avec les références de Vue
-
Nous en avons presque terminé avec Vue. La dernière fonctionnalité à implanter est la gestion de la mise au point, ou en d'autres termes, la façon dont nous pouvons améliorer l'accessibilité du clavier de notre application. Nous allons examiner l'utilisation des références de Vue pour gérer cela, une fonctionnalité avancée qui vous permet d'avoir un accès direct aux nœuds DOM sous-jacents sous le DOM virtuel, ou un accès direct d'un composant à la structure DOM interne d'un composant enfant.
-
9. Ressources Vue
-
Nous allons maintenant terminer notre étude de Vue en vous donnant une liste de ressources que vous pouvez utiliser pour aller plus loin dans votre apprentissage, ainsi que d'autres conseils utiles.
-
- -

Tutoriels sur Svelte

- -
-

Note : Les tutoriels sur Svelte ont été essayés pour la dernière fois en aout 2020, avec Svelte 3.24.1.

- -

Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version terminée de l'exemple eu code de l'application Svelte (tel qu'il est après chaque chapitre) dans le dépôt mdn-svelte-tutorial. Pour une version exécutable en direct, voir https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2.

-
- -
-
1. Premiers pas avec Svelte
-
Dans cet articles, nous vous proposerons une brève introduction au framework Svelte. Nous verrons comment Svelte fonctionne et qu'est-ce qui le rend si différent des autrse frameworks et outils que nous avons vus jusqu'à présent. Ensuite, nous apprendronds à mettre en place notre environnement de développement, créerons une application démonstrative, appréhenderons la structure du projet et nous verrons comment la mettre en oeuvre localement puis la compiler pour la mettre en production.
-
- -
-
2. Commencer notre application todolist avec Svelte
-
Maintenant que nous avons compris les bases du fonctionnement  de Svelte, nous pouvons commencer à construirer application démonstrative : une liste de tâches. Dans cet article, nous verrons d'abord les fonctionnalités attendues dans notre application, puis nous créerons un composant Todos.svelte et mettrons en place un HTML statique et du CSS, prêts pour commencer le développement des fonctionnalités de notre application de liste de tâches avec laquelle nous continuerons dans les articles suivants.
-
3. Comportements dynamiques dans Svelte : travailler avec les variables et les propriétés
-
Maintenant que nous avons HTML et notre CSS, nous pouvons commencer le développement des fonctionnalités attendues pour notre application de liste de tâches Svelte. Dans cet article, nous utiliserons des variables et propriétés pour rendre notre application dynamique, nous permettant d'ajouter et de supprimer des tâches, de les marquer comme terminées et de les filter par état.
-
4. Diviser notre application Svelte en composants
-
L'objectif principal de cet article est de voir comment nous pouvons diviser notre application en composants gérables et partager l'information entre eux. Nous décomposerons notre application puis y ajouterons plus de fonctionnalités pour permettre aux utilisateurs de modifier des composants existants.
-
5. Svelte avancé : réactivité, cycle de vie et accessibilité
-
Dans cet articles, nous ajouterons les dernières fonctionnalités de l'application et nous pousserons la décomposition de notre application encore plus loin. Nous apprendrons comment résoudre des problèmes de réactivité liés à la mise à jour d'objets et de tableaux. Pour éviter les erreurs communes, nous devrons nous explorer plus profondément le système de réactivité de Svelte. nous verrons aussi comment résoudre certaines problèmes de mise au point pour l'accessibilité et plus encore.
-
6. Travailler avec le stockage de Svelte
-
Dans cet article, nous vous montrerons une autre manière de gérer les états avec Svelte : les stockages Stores. Les Stores sont des répertoires de données globaux qui contiennent des valeurs. Les composants peuvent s'abonner aux stockages et recevoir des notifications que leurs valeurs changent.
-
7. Support de TypeScript avec Svelte
-
Nous allons maintenant apprendre à utiliser TypeScript dans nos applications Svelte. D'abord, nous apprendrons ce qu'est TypeScript et quels bénéfices il peut nous apporter, puis nous verrons ensemble comment configurer notre projet pour travailler avec des fichiers TypeScript. Enfin, nous parcourerons notre application pour voir ce que nous pouvons y changer pour tirer pleinement parti des fonctionnalités de TypeScript.
-
8. Déploiement et étapes suivantes
-
Dans ce dernier article, nous verrons comment déployer votre application et la mettre en ligne et nous vous partagerons quelques-unes des ressources auxquelles vous devriez jeter un oeil pour poursuivre votre apprentissage de Svelte.
-
- -

Quels frameworks avons-nous choisis ?

- -

Nous publions notre première série d'articles accompagné de guides axés sur quatre frameworks. Trois d'entre eux sont très populaires et bien établis (React/ReactDOM, Ember et Vue) tandis que Svelte est un nouveau prometteur et qui a déjà gagné beaucoup en popularité dernièrement.

- -

Il existe plusieurs raisons à ceci :

- - - -

Disons-le franchement : nous n'avons pas choisi les frameworks sur lesquels nous nous concentrons parce que nous pensons qu'ils sont les meilleurs ou parce que nous les soutenons de quelque manière que ce soit. Nous pensons seulement qu'ils correspondent le mieux aux critères établis ci-avant.

- -

Notez que nous espérions avoir plus de frameworks inclus lors de la publication initiale, mais nous avons décidé de publier le contenu, puis d'ajouter plus de guides de framework plus tard plutôt que de le retarder l'édition. Si votre framework préféré n'est pas représenté dans ce contenu et que vous souhaitez faire changer cela, n'hésitez pas à en discuter avec nous ! Contactez-nous via Matrix, ou Discourse, ou envoyez-nous un mail sur la liste mdn-admins.

+**[Commencez dès maintenant, avec "Introduction aux frameworks côté client"](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction)** + +## Prérequis + +Vous devez vraiment connaitre les bases des principaux langages du web ([HTML](/fr/docs/Learn/HTML), [CSS](/fr/docs/Learn/CSS), et particulièrement [JavaScript](/fr/docs/Learn/JavaScript)) avant d'essayer de vous lancer dans l'apprentissage des frameworks côté client. + +Votre code n'en sera que plus qualitatif et plus professionnel, et vous serez en mesure de résoudre vos problèmes avec plus de confiance si vous comprenez les fonctionnalités fondamentales du web sur lesquelles les frameworks s'appuient. + +### Vous voulez devenir développeur web front-end ? + +Nous avons créé un cours qui inclut toutes les informations essentielles dont vous avez besoin pour atteindre votre objectif. + +[Commencer](/fr/docs/Learn/Front-end_web_developer) + +## Guides d'introduction + +- [1. Introduction aux frameworks côté client](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) + - : Nous commençons notre aperçu des frameworks par un tour d'horizon général du domaine, notamment en regardant un bref historique de JavaScript et des frameworks, la raison pour laquelle les frameworks existent et ce qu'ils nous proposent, comment commencer à réfléchir au choix d'un framework à apprendre et quelles alternatives il y a aux frameworks côté client. +- [2. Principales caractéristiques du Framework](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) + - : Chaque framework JavaScript majeur a une approche différente de la mise à jour du DOM, de la gestion des évènements du navigateur et de la manière dont rendre l'expérience de développement agréable. Cet article explorera les principales caractéristiques des 4 grands frameworks, en examinant comment les frameworks ont tendance à fonctionner à un haut niveau et les différences entre eux. + +## Tutoriels sur React + +> **Note :** Les tutoriels sur React ont été essayés pour la dernière fois en mai 2020, avec React/ReactDOM 16.13.1 et create-react-app 3.4.1. +> +> Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version finale de l'exemple de code d'application React dans notre [todo-react repository](https://github.com/mdn/todo-react). Pour une version exécutable en direct, voir . + +- [1. Premier pas avec React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - : Dans cet article, nous dirons bonjour à React. Nous découvrirons les prémices de son fonctionnement et de ses cas d'utilisation, configurerons une chaine d'outils React de base sur notre ordinateur local et créerons et jouerons avec une application de démarrage simple, en apprenant un peu plus sur le fonctionnement de React dans le processus. +- [2. Début de notre liste de tâches React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - : Supposons que nous ayons été chargés de créer une preuve de concept dans React – une application qui permet aux utilisateurs d'ajouter, de modifier et de supprimer les tâches sur lesquelles ils souhaitent travailler, ainsi que de marquer les tâches comme terminées sans les supprimer. Cet article vous guidera tout au long de la mise en place de la structure et du style des composants de base de l'application, prêts pour la définition et l'interactivité des composants individuels, que nous ajouterons plus tard. +- [3. Diviser notre application React en composants](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - : À ce stade, notre application est un monolithe. Avant de pouvoir lui faire faire des choses, nous devons le diviser en composants descriptifs gérables. React n'a pas de règles strictes pour ce qui est et n'est pas un composant - c'est à vous de décider ! Dans cet article, nous allons vous montrer un moyen judicieux de diviser notre application en composants. +- [4. Interactivité de React: évènements et états](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - : Une fois notre plan de composants élaboré, il est maintenant temps de commencer à faire évoluer notre application d'une interface utilisateur complètement statique vers une interface qui nous permet réellement d'interagir et de modifier des choses. Dans cet article, nous allons le faire, en explorant les évènements et les états en cours de route. +- [5. Interactivité de React: modification, filtrage, rendu conditionné](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - : Alors que nous approchons de la fin de notre voyage React (pour l'instant du moins), nous ajouterons la touche finale aux principaux domaines de fonctionnalités de notre application de liste de tâches. Cela comprend la possibilité de modifier les tâches existantes et de filtrer la liste des tâches entre toutes les tâches, terminées et incomplètes. Nous examinerons le rendu conditionné de l'interface utilisateur en cours de route. +- [6. Accessibilité dans React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - : Dans notre avant-dernier article du tutoriel, nous nous concentrerons sur l'accessibilité, y compris la gestion de la mise au point dans React, ce qui peut améliorer la convivialité et réduire la confusion pour les utilisateurs de clavier uniquement et de lecteur d'écran. +- [7. Ressources sur React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + - : Notre dernier article vous fournit une liste de ressources sur React que vous pouvez utiliser pour aller plus loin dans votre apprentissage. + +## Tutoriels sur Ember + +> **Note :** Les tutoriels Ember ont été essayés pour la dernière fois en Mai 2020, avec Ember/Ember CLI version 3.18.0. +> +> Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version finale de l'exemple de code d'application Ember dans le Ember app code in the [ember-todomvc-tutorial repository](https://github.com/NullVoxPopuli/ember-todomvc-tutorial/tree/master/steps/00-finished-todomvc/todomvc). Pour une version exécutable en direct, voir (cela inclut également quelques fonctionnalités supplémentaires non couvertes dans le tutoriel). + +- [1. Premiers pas avec Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - : Dans notre premier article sur Ember, nous verrons comment fonctionne Ember et ce à quoi il sert, installerons la chaine d'outils d'Ember localement, créerons un exemple d'application, puis effectuerons une configuration initiale pour la préparer au développement. +- [2. Structure et composant de l'application Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - : Dans cet article, nous commencerons à planifier la structure de notre application TodoMVC Ember, à ajouter du code HTML correspondant, puis nous diviserons cette structure HTML en composants. +- [3. Interactivité Ember : évènements, classes et états](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - : À ce stade, nous allons commencer à ajouter de l'interactivité à notre application, offrant la possibilité d'ajouter et d'afficher de nouveaux éléments à notre liste. En cours de route, nous examinerons l'utilisation d'évènements dans Ember, la création de classes de composants pour contenir du code JavaScript pour contrôler les fonctionnalités interactives et la configuration d'un service pour suivre l'état des données de notre application. +- [4. Interactivité Ember : fonctionnalité du Footer, rendu conditionné](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - : Il est maintenant temps de commencer à aborder la fonctionnalité de footer dans notre application. Ici, nous allons mettre à jour le compteur de tâches pour afficher le nombre correct de tâches à compléter et appliquer correctement le style aux tâches terminées (c'est-à-dire là dont la case a été cochée). Nous allons également câbler notre bouton "Effacer terminé". En cours de route, nous découvrirons comment utiliser le rendu conditionné dans nos modèles. +- [5. Routage dans Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - : Dans cet article, nous apprendrons les bases du routage avec Ember. Nous l'utiliserons pour fournir une URL unique pour chacune des trois vues à faire : "Tous", "Actif", et "Terminé". +- [6. Ressources sur Ember et dépannage](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + - : Notre dernier article sur Ember vous fournit une liste de ressources que vous pouvez utiliser pour aller plus loin dans votre apprentissage, ainsi que des dépannages utiles et d'autres informations. + +## Tutoriels sur Vue + +> **Note :** Les tutoriels sur Vue ont été essayés pour la dernière fois en mai 2020, avec Vue 2.6.11. +> +> Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version terminée de l'exemple de code d'application Vue dans notre [todo-vue repository](https://github.com/mdn/todo-vue). Pour une version exécutable en direct, voir . + +- [1. Premiers pas avec Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - : Maintenant, introduisons Vue, le troisième de nos frameworks. Dans cet article, nous allons examiner un peu le contexte de Vue, apprendre à l'installer et créer un nouveau projet, étudier la structure de haut niveau de l'ensemble du projet et d'un composant individuel, voir comment exécuter le projet localement, et préparez-le à commencer à construire notre exemple. +- [2. Création de notre premier composant Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - : Il est maintenant temps de plonger plus profondément dans Vue et de créer notre propre composant personnalisé (nous commencerons par créer un composant pour représenter chaque élément de la liste de tâches). En cours de route, nous découvrirons quelques concepts importants tels que l'appel de composants à l'intérieur d'autres composants, leur transmission de données via des accessoires et l'enregistrement de l'état des données. +- [3. Rendu d'une liste de composants Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - : À ce stade, nous avons un composant entièrement fonctionnel ; nous sommes maintenant prêts à ajouter plusieurs composants `ToDoItem` à notre application. Dans cet article, nous examinerons l'ajout d'un ensemble de données d'élément todo à notre composant `App.vue` que nous allons ensuite parcourir et afficher à l'intérieur des composants `ToDoItem` à l'aide de la directive `v-for`. +- [4. Ajout d'un nouveau formulaire todo: évènements, méthodes, et modèles Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - : Nous avons maintenant des exemples de données en place et une boucle qui prend chaque bit de données et le rend dans un `ToDoItem` dans notre application. Ce dont nous avons vraiment besoin ensuite, c'est la possibilité de permettre à nos utilisateurs de saisir leurs propres éléments à faire dans l'application, et pour cela, nous aurons besoin d'un texte ``, un évènement à déclencher lorsque les données sont soumises, une méthode de déclenchement lors de la soumission pour ajouter les données et relancer la liste, et un modèle pour contrôler les données. C'est ce que nous allons couvrir dans cet article. +- [5. Styliser les composants Vue avec CSS](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - : Le moment est enfin venu de rendre notre application un peu plus jolie. Dans cet article, nous explorerons les différentes façons de styliser les composants Vue avec CSS. +- [6. Utilisation des propriétés calculées de Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - : Dans cet article, nous allons ajouter un compteur qui affiche le nombre d'éléments à faire terminés, en utilisant une fonctionnalité de Vue appelée propriétés calculées. Celles-ci fonctionnent de la même manière que les méthodes, mais ne sont réexécutées que lorsque l'une de leurs dépendances change. +- [7. Rendu conditionnel Vue : éditer les todos existants](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - : Il est maintenant temps d'ajouter l'un des éléments majeurs de la fonctionnalité qui nous manque toujours: la possibilité de modifier les éléments todos existants. Pour ce faire, nous profiterons des capacités de rendu conditionnel de Vue — à savoir `v-if` et `v-else` — pour nous permettre de basculer entre la vue d'élément todo existante et une vue d'édition où vous pouvez mettre à jour les étiquettes d'élément todo. Nous examinerons également l'ajout de fonctionnalités pour supprimer les éléments todo. +- [8. Gestion de la mise au poinr avec les références de Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - : Nous en avons presque terminé avec Vue. La dernière fonctionnalité à implanter est la gestion de la mise au point, ou en d'autres termes, la façon dont nous pouvons améliorer l'accessibilité du clavier de notre application. Nous allons examiner l'utilisation des références de Vue pour gérer cela, une fonctionnalité avancée qui vous permet d'avoir un accès direct aux nœuds DOM sous-jacents sous le DOM virtuel, ou un accès direct d'un composant à la structure DOM interne d'un composant enfant. +- [9. Ressources Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + - : Nous allons maintenant terminer notre étude de Vue en vous donnant une liste de ressources que vous pouvez utiliser pour aller plus loin dans votre apprentissage, ainsi que d'autres conseils utiles. + +## Tutoriels sur Svelte + +> **Note :** Les tutoriels sur Svelte ont été essayés pour la dernière fois en aout 2020, avec Svelte 3.24.1. +> +> Si vous avez besoin de vérifier votre code par rapport à notre version, vous pouvez trouver une version terminée de l'exemple eu code de l'application Svelte (tel qu'il est après chaque chapitre) dans le dépôt [mdn-svelte-tutorial](https://github.com/opensas/mdn-svelte-tutorial). Pour une version exécutable en direct, voir . + +- [1. Premiers pas avec Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - : Dans cet articles, nous vous proposerons une brève introduction au framework Svelte. Nous verrons comment Svelte fonctionne et qu'est-ce qui le rend si différent des autrse frameworks et outils que nous avons vus jusqu'à présent. Ensuite, nous apprendronds à mettre en place notre environnement de développement, créerons une application démonstrative, appréhenderons la structure du projet et nous verrons comment la mettre en oeuvre localement puis la compiler pour la mettre en production. + + + +- [2. Commencer notre application todolist avec Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - : Maintenant que nous avons compris les bases du fonctionnement  de Svelte, nous pouvons commencer à construirer application démonstrative : une liste de tâches. Dans cet article, nous verrons d'abord les fonctionnalités attendues dans notre application, puis nous créerons un composant Todos.svelte et mettrons en place un HTML statique et du CSS, prêts pour commencer le développement des fonctionnalités de notre application de liste de tâches avec laquelle nous continuerons dans les articles suivants. +- [3. Comportements dynamiques dans Svelte : travailler avec les variables et les propriétés](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - : Maintenant que nous avons HTML et notre CSS, nous pouvons commencer le développement des fonctionnalités attendues pour notre application de liste de tâches Svelte. Dans cet article, nous utiliserons des variables et propriétés pour rendre notre application dynamique, nous permettant d'ajouter et de supprimer des tâches, de les marquer comme terminées et de les filter par état. +- [4. Diviser notre application Svelte en composants](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - : L'objectif principal de cet article est de voir comment nous pouvons diviser notre application en composants gérables et partager l'information entre eux. Nous décomposerons notre application puis y ajouterons plus de fonctionnalités pour permettre aux utilisateurs de modifier des composants existants. +- [5. Svelte avancé : réactivité, cycle de vie et accessibilité](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - : Dans cet articles, nous ajouterons les dernières fonctionnalités de l'application et nous pousserons la décomposition de notre application encore plus loin. Nous apprendrons comment résoudre des problèmes de réactivité liés à la mise à jour d'objets et de tableaux. Pour éviter les erreurs communes, nous devrons nous explorer plus profondément le système de réactivité de Svelte. nous verrons aussi comment résoudre certaines problèmes de mise au point pour l'accessibilité et plus encore. +- [6. Travailler avec le stockage de Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - : Dans cet article, nous vous montrerons une autre manière de gérer les états avec Svelte : les stockages Stores. Les Stores sont des répertoires de données globaux qui contiennent des valeurs. Les composants peuvent s'abonner aux stockages et recevoir des notifications que leurs valeurs changent. +- [7. Support de TypeScript avec Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - : Nous allons maintenant apprendre à utiliser TypeScript dans nos applications Svelte. D'abord, nous apprendrons ce qu'est TypeScript et quels bénéfices il peut nous apporter, puis nous verrons ensemble comment configurer notre projet pour travailler avec des fichiers TypeScript. Enfin, nous parcourerons notre application pour voir ce que nous pouvons y changer pour tirer pleinement parti des fonctionnalités de TypeScript. +- [8. Déploiement et étapes suivantes](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) + - : Dans ce dernier article, nous verrons comment déployer votre application et la mettre en ligne et nous vous partagerons quelques-unes des ressources auxquelles vous devriez jeter un oeil pour poursuivre votre apprentissage de Svelte. + +## Quels frameworks avons-nous choisis ? + +Nous publions notre première série d'articles accompagné de guides axés sur quatre frameworks. Trois d'entre eux sont très populaires et bien établis (React/ReactDOM, Ember et Vue) tandis que Svelte est un nouveau prometteur et qui a déjà gagné beaucoup en popularité dernièrement. + +Il existe plusieurs raisons à ceci : + +- Ce sont des outils populaires qui dureront un certain temps – comme avec tout outil logiciel, il est bon de s'en tenir à des outils activement développés et qui ne seront probablement pas interrompus la semaine prochaine et qui constitueront des atouts considérables à vos compétences lorsque vous cherchez un emploi, +- Ils ont des communautés solides et de bonnes documentations. C'est très important pour être en mesure de recevoir de l'aide lors de votre apprentissage d'un sujet complexe, surtout lorsque vous débutez. +- Nous n'avons pas les ressources nécessaires pour couvrir _tous_ les frameworks modernes. De toute façon, cette liste serait très difficile à tenir à jour car de nouveaux apparaissent tout le temps. +- En tant que débutant, choisir sur quoi se pencher parmi le grand nombre de choix disponibles est un problème très réel. Faire en sorte que cette liste soit courte est donc utile. + +Disons-le franchement : nous n'avons **pas** choisi les frameworks sur lesquels nous nous concentrons parce que nous pensons qu'ils sont les meilleurs ou parce que nous les soutenons de quelque manière que ce soit. Nous pensons seulement qu'ils correspondent le mieux aux critères établis ci-avant. + +Notez que nous espérions avoir plus de frameworks inclus lors de la publication initiale, mais nous avons décidé de publier le contenu, puis d'ajouter plus de guides de framework plus tard plutôt que de le retarder l'édition. Si votre framework préféré n'est pas représenté dans ce contenu et que vous souhaitez faire changer cela, n'hésitez pas à en discuter avec nous ! Contactez-nous via [Matrix](https://wiki.mozilla.org/Matrix), ou [Discourse](https://discourse.mozilla.org/c/mdn), ou envoyez-nous un mail sur la [liste mdn-admins](mailto:mdn-admins@mozilla.org). diff --git a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/introduction/index.md b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/introduction/index.md index d222a30518..711019d139 100644 --- a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/introduction/index.md +++ b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/introduction/index.md @@ -3,93 +3,102 @@ title: Introduction aux frameworks côté client slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction --- -
{{LearnSidebar}}
+{{LearnSidebar}}{{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
{{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
- -

We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.

+We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks. - - - - - - - - - - + + + + + + + + + +
Prerequisites:Familiarity with the core HTML, CSS, and JavaScript languages.
Objective:To understand how client-side JavaScript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one.
Prerequisites: + Familiarity with the core HTML, + CSS, and + JavaScript languages. +
Objective: + To understand how client-side JavaScript frameworks came to exist, what + problems they solve, what alternatives there are, and how to go about + choosing one. +
-

A brief history

+## A brief history -

When JavaScript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents. The web became not just a place to read things, but to do things. JavaScript’s popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called libraries, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web.

+When JavaScript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents. The web became not just a place to _read things_, but to _do things_. JavaScript’s popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called **libraries**, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web. -

Now, JavaScript is an essential part of the web, used on 95% of all websites, and the web is an essential part of modern life. Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio or video chat. The web allows us to do things that used to be possible only in native applications installed on our computers. These modern, complex, interactive websites are often referred to as web applications.

+Now, JavaScript is an essential part of the web, [used on 95% of all websites](https://w3techs.com/technologies/details/cp-javascript), and the web is an essential part of modern life. Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio or video chat. The web allows us to do things that used to be possible only in native applications installed on our computers. These modern, complex, interactive websites are often referred to as **web applications**. -

The advent of modern JavaScript frameworks has made it much easier to build highly dynamic, interactive applications. A framework is a library that offers opinions about how software gets built. These opinions allow for predictability and homogeneity in an application; predictability allows software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software.

+The advent of modern JavaScript frameworks has made it much easier to build highly dynamic, interactive applications. A **framework** is a library that offers opinions about how software gets built. These opinions allow for predictability and homogeneity in an application; predictability allows software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software. -

JavaScript frameworks power much of the impressive software on the modern web – including many of the websites you likely use every day. MDN Web Docs, which you are currently reading this on, uses the React/ReactDOM framework to power its front end.

+JavaScript frameworks power much of the impressive software on the modern web – including many of the websites you likely use every day. MDN Web Docs, which you are currently reading this on, uses the React/ReactDOM framework to power its front end. -

What frameworks are out there?

+## What frameworks are out there? -

There are many frameworks out there, but currently the "big four" are considered to be the following.

+There are many frameworks out there, but currently the "big four" are considered to be the following. -

Ember

+### Ember -

Ember was initially released in December 2011 as a continuation of work that started in the SproutCore project. It is an older framework that has less users than more modern alternatives  such as React and Vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles.

+[Ember](https://emberjs.com/) was initially released in December 2011 as a continuation of work that started in the [SproutCore](https://en.wikipedia.org/wiki/SproutCore) project. It is an older framework that has less users than more modern alternatives  such as React and Vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles. -

Start learning Ember

+[Start learning Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) -

Angular

+### Angular -

Angular is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a complete rewrite from the same team that built AngularJS. Angular was officially released on the 14th of September 2016.

+[Angular](https://angular.io) is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a complete rewrite from the same team that built [AngularJS](https://angularjs.org/). Angular was officially released on the 14th of September 2016. -

Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions. Angular uses TypeScript, a superset of JavaScript that we’ll look at in a little more detail in the next chapter.

+Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions. Angular uses [TypeScript](https://www.typescriptlang.org/), a superset of JavaScript that we’ll look at in a little more detail in the next chapter. -

Vue

+### Vue -

Evan You first released Vue in 2014, after working on and learning from the original AngularJS project. Vue is the youngest of the big four, but has enjoyed a recent uptick in popularity.

+Evan You first released [Vue](https://vuejs.org/) in 2014, after working on and learning from the original [AngularJS](https://angularjs.org/) project. Vue is the youngest of the big four, but has enjoyed a recent uptick in popularity. -

Vue, like AngularJS, extends HTML with some of its own code. Apart from that, it mainly relies on modern, standard JavaScript.

+Vue, like [AngularJS](https://angularjs.org/), extends HTML with some of its own code. Apart from that, it mainly relies on modern, standard JavaScript. -

Start learning Vue

+[Start learning Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) -

React

+### React -

Facebook released React in 2013. By this point, it had already been using React to solve many of its problems internally. React itself is not technically a framework; it's a library for rendering UI components. React is used in combination with other libraries to make applications — React and React Native enable developers to make mobile applications; React and ReactDOM enable them to make web applications, etc.

+Facebook released [React](https://reactjs.org/) in 2013. By this point, it had already been using React to solve many of its problems internally. React itself is _not_ technically a framework; it's a library for rendering UI components. React is used in combination with _other_ libraries to make applications — React and [React Native](https://reactnative.dev/) enable developers to make mobile applications; React and [ReactDOM](https://reactjs.org/docs/react-dom.html) enable them to make web applications, etc. -

Because React and ReactDOM are so often used together, React is colloquially understood as a JavaScript framework. As you read through this module, we will be working with that colloquial understanding.

+Because React and ReactDOM are so often used together, React is colloquially understood as a JavaScript framework. As you read through this module, we will be working with that colloquial understanding. -

React extends JavaScript with HTML-like syntax, known as JSX.

+React extends JavaScript with HTML-like syntax, known as [JSX](https://reactjs.org/docs/introducing-jsx.html). -

Start learning React

+[Start learning React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) -

Why do frameworks exist?

+## Why do frameworks exist? -

We've discussed the environment that inspired the creation of frameworks, but not really why developers felt the need to make them. Exploring the why requires first examining the challenges of software development.

+We've discussed the environment that inspired the creation of frameworks, but not really _why_ developers felt the need to make them. Exploring the why requires first examining the challenges of software development. -

Consider a common kind of application: A to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters. This application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. In software development, this underlying data is known as state.

+Consider a common kind of application: A to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters. This application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. In software development, this underlying data is known as state. -

Each of our goals is theoretically simple in isolation. We can iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task. When we remember that the application has to let the user to do all of these things through the browser, however, some cracks start to show. The real problem is this: every time we change our application’s state, we need to update the UI to match.

+Each of our goals is theoretically simple in isolation. We can iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task. When we remember that the application has to let the user to do _all_ of these things through the browser, however, some cracks start to show. **The real problem is this: every time we change our application’s state, we need to update the UI to match.** -

We can examine the difficulty of this problem by looking at just one feature of our todo list app: rendering a list of tasks.

+We can examine the difficulty of this problem by looking at just _one_ feature of our todo list app: rendering a list of tasks. -

The verbosity of DOM changes

+## The verbosity of DOM changes -

Building HTML elements and rendering them in the browser at the appropriate time takes a surprising amount of code. Let's say that our state is an array of objects structured like this:

+Building HTML elements and rendering them in the browser at the appropriate time takes a surprising amount of code. Let's say that our state is an array of objects structured like this: -
const state = [
+```js
+const state = [
   {
     id: 'todo-0',
     name: 'Learn some frameworks!'
   }
-]
+] +``` -

How do we show one of those tasks to our user? We want to represent each task as a list item – an HTML <li> element inside of an unordered list element (a <ul>). How do we make it? That could look something like this:

+How do we show one of those tasks to our user? We want to represent each task as a list item – an HTML [`
  • `](/fr/docs/Web/HTML/Element/li) element inside of an unordered list element (a [`
      `](/fr/docs/Web/HTML/Element/ul)). How do we make it? That could look something like this: -
      function buildTodoItemEl(id, name) {
      +```js
      +function buildTodoItemEl(id, name) {
         const item = document.createElement('li');
         const span = document.createElement('span');
         const textContent = document.createTextNode(name);
      @@ -101,13 +110,15 @@ translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introd
         item.appendChild(buildDeleteButtonEl(id));
       
         return item;
      -}
      +} +``` -

      Here, we use the document.createElement() method to make our <li>, and several more lines of code to create the properties and children it needs.

      +Here, we use the [`document.createElement()`](/fr/docs/Web/API/Document/createElement) method to make our `
    • `, and several more lines of code to create the properties and children it needs. -

      The tenth line of this snippet references another build function: buildDeleteButtonEl(). It follows a similar pattern to the one we used to build a list item element:

      +The tenth line of this snippet references another build function: `buildDeleteButtonEl()`. It follows a similar pattern to the one we used to build a list item element: -
      function buildDeleteButtonEl(id) {
      +```js
      +function buildDeleteButtonEl(id) {
         const button = document.createElement('button');
         const textContent = document.createTextNode('Delete');
       
      @@ -115,13 +126,15 @@ translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introd
         button.appendChild(textContent);
       
         return button;
      -}
      +} +``` -

      This button doesn't do anything yet, but it will later once we decide to implement our delete feature. The code that will render our items on the page might read something like this:

      +This button doesn't do anything yet, but it will later once we decide to implement our delete feature. The code that will render our items on the page might read something like this: -
      function renderTodoList() {
      +```js
      +function renderTodoList() {
         const frag = document.createDocumentFragment();
      -  state.tasks.forEach(task => {
      +  state.tasks.forEach(task => {
           const item = buildTodoItemEl(task.id, task.name);
           frag.appendChild(item);
         });
      @@ -130,276 +143,228 @@ translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introd
           todoListEl.removeChild(todoListEl.firstChild);
         }
         todoListEl.appendChild(frag);
      -}
      +} +``` + +We've now got well over thirty lines of code dedicated _just_ to the UI – _just_ to the step of rendering something in the DOM – and at no point do we add classes that we could use later to style our list-items! + +Working directly with the DOM, as in this example, requires understanding many things about how the DOM works: how to make elements; how to change their properties; how to put elements inside of each other; how to get them on the page. None of this code actually handles user interactions, or addresses adding or deleting a task. If we add those features, we have to remember to update our UI in the right time and in the right way. + +JavaScript frameworks were created to make this kind of work a little easier — they exist to provide a better _developer experience_. They don't bring brand-new powers to JavaScript; they give you easier access to JavaScript's powers so you can build for today's web. -

      We've now got well over thirty lines of code dedicated just to the UI – just to the step of rendering something in the DOM – and at no point do we add classes that we could use later to style our list-items!

      +If you want to see code samples from this section in action, you can check out a [working version of the app on CodePen](https://codepen.io/dengeist/pen/XWbPNmw), which also allows users to add and delete new tasks. -

      Working directly with the DOM, as in this example, requires understanding many things about how the DOM works: how to make elements; how to change their properties; how to put elements inside of each other; how to get them on the page. None of this code actually handles user interactions, or addresses adding or deleting a task. If we add those features, we have to remember to update our UI in the right time and in the right way.

      +Read more about the JavaScript used in this section: -

      JavaScript frameworks were created to make this kind of work a little easier — they exist to provide a better developer experience. They don't bring brand-new powers to JavaScript; they give you easier access to JavaScript's powers so you can build for today's web.

      +- [`document.createElement()`](/fr/docs/Web/API/Document/createElement) +- [`document.createTextNode()`](/fr/docs/Web/API/Document/createTextNode) +- [`document.createDocumentFragment()`](/fr/docs/Web/API/Document/createDocumentFragment) +- [`eventTarget.addEventListener()`](/fr/docs/Web/API/EventTarget/addEventListener) +- [`node.appendChild()`](/fr/docs/Web/API/Node/appendChild) +- [`node.removeChild()`](/fr/docs/Web/API/Node/removeChild) -

      If you want to see code samples from this section in action, you can check out a working version of the app on CodePen, which also allows users to add and delete new tasks.

      +## Another way to build UIs -

      Read more about the JavaScript used in this section:

      +Every JavaScript framework offers a way to write user interfaces more _declaratively_. That is, they allow you to write code that describes how your UI should look, and the framework makes it happen in the DOM behind the scenes. +The vanilla JavaScript approach to building out new DOM elements in repetition was difficult to understand at a glance.  By contrast, the following block of code illustrates the way you might use Vue to describe our list of tasks: + +```html +``` -

      Another way to build UIs

      +That's it. This snippet reduces approximately thirty-two lines of code down to six lines. If the curly braces and `v-` attributes here are unfamiliar to you, that's okay; you’ll learn about Vue-specific syntax later on in the module. The thing to take away here is that this code looks like the UI it represents, whereas the vanilla JavaScript code does not. -

      Every JavaScript framework offers a way to write user interfaces more declaratively. That is, they allow you to write code that describes how your UI should look, and the framework makes it happen in the DOM behind the scenes.

      +Thanks to Vue, we didn't have to write our own functions for building the UI; the framework will handle that for us in an optimized, efficient way. Our only role here was to describe to Vue what each item should look like. Developers who are familiar with Vue can join our project and quickly work out what is going on. Vue is not alone in this: using a framework improves team as well as individual efficiency. -

      The vanilla JavaScript approach to building out new DOM elements in repetition was difficult to understand at a glance.  By contrast, the following block of code illustrates the way you might use Vue to describe our list of tasks:

      +It's possible to do things _similar_ to this in vanilla JavaScript. [Template literal strings](/fr/docs/Web/JavaScript/Reference/Template_literals) make it easy to write strings of HTML that represent what the final element would look like. That might be a useful idea for something as simple as our to-do list application, but it's not maintainable for large applications that manage thousands of records of data, and could render just as many unique elements in a user interface. -
      <ul>
      -  <li v-for="task in tasks" v-bind:key="task.id">
      -    <span>\{{task.name\}}</span>
      -    <button type="button">Delete</button>
      -  </li>
      -</ul>
      +## Other things frameworks give us -

      That's it. This snippet reduces approximately thirty-two lines of code down to six lines. If the curly braces and v- attributes here are unfamiliar to you, that's okay; you’ll learn about Vue-specific syntax later on in the module. The thing to take away here is that this code looks like the UI it represents, whereas the vanilla JavaScript code does not.

      +Let's look at some of the other advantages conferred upon us by frameworks. As we've alluded to before, the advantages of frameworks are achievable in vanilla JavaScript, but using a framework takes away all of the cognitive load of having to solve these problems yourself. -

      Thanks to Vue, we didn't have to write our own functions for building the UI; the framework will handle that for us in an optimized, efficient way. Our only role here was to describe to Vue what each item should look like. Developers who are familiar with Vue can join our project and quickly work out what is going on. Vue is not alone in this: using a framework improves team as well as individual efficiency.

      +### Tooling -

      It's possible to do things similar to this in vanilla JavaScript. Template literal strings make it easy to write strings of HTML that represent what the final element would look like. That might be a useful idea for something as simple as our to-do list application, but it's not maintainable for large applications that manage thousands of records of data, and could render just as many unique elements in a user interface.

      +Because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that Improves the developer experience. These tools make it easy to add things like testing (to ensure that your application behaves as it should) or linting (to ensure that your code is error-free and stylistically consistent). -

      Other things frameworks give us

      +> **Note :** If you want to find out more details about web tooling concepts, have a read of our [Client-side tooling overview](/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview). -

      Let's look at some of the other advantages conferred upon us by frameworks. As we've alluded to before, the advantages of frameworks are achievable in vanilla JavaScript, but using a framework takes away all of the cognitive load of having to solve these problems yourself.

      +### Compartmentalization -

      Tooling

      +Most major frameworks encourage developers to abstract the different parts of their user interfaces into _components_ — maintainable, reusable chunks of code that can communicate with one another. All the code related to a given component can live in one file (or a couple of specific files), so that you as a developer know exactly where to go to make changes to that component. In a vanilla JavaScript app, you'd have to create your own set of conventions to achieve this in an efficient, scalable way. Many JavaScript developers, if left to their own devices, could end up with all the code related to one part of the UI being spread out all over a file — or in another file altogether. -

      Because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that Improves the developer experience. These tools make it easy to add things like testing (to ensure that your application behaves as it should) or linting (to ensure that your code is error-free and stylistically consistent).

      +### Routing -
      -

      Note : If you want to find out more details about web tooling concepts, have a read of our Client-side tooling overview.

      -
      +The most essential feature of the web is that it allows users to navigate from one page to another – it is, after all, a network of interlinked documents. When you follow a link on this very website, your browser communicates with a server and fetches new content to display for you. As it does so, the URL in your address bar changes. You can save this new URL and come back to the page later on, or share it with others so they can easily find the same page. Your browser remembers your navigation history and allows you to navigate back and forth, too. This is called **server-side routing**. -

      Compartmentalization

      +Modern web applications typically do not fetch and render new HTML files — they load a single HTML shell, and continually update the DOM inside it (referred to as **single page apps**, or **SPAs**) without navigating users to new addresses on the web. Each new pseudo-webpage is usually called a _view_, and by default, no routing is done. -

      Most major frameworks encourage developers to abstract the different parts of their user interfaces into components — maintainable, reusable chunks of code that can communicate with one another. All the code related to a given component can live in one file (or a couple of specific files), so that you as a developer know exactly where to go to make changes to that component. In a vanilla JavaScript app, you'd have to create your own set of conventions to achieve this in an efficient, scalable way. Many JavaScript developers, if left to their own devices, could end up with all the code related to one part of the UI being spread out all over a file — or in another file altogether.

      +When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in this fashion, it is aptly called **client-side routing**. -

      Routing

      +It's _possible_ to make a router using the native capabilities of JavaScript and the browser, but popular, actively developed frameworks have companion libraries that make routing a more intuitive part of the development process. -

      The most essential feature of the web is that it allows users to navigate from one page to another – it is, after all, a network of interlinked documents. When you follow a link on this very website, your browser communicates with a server and fetches new content to display for you. As it does so, the URL in your address bar changes. You can save this new URL and come back to the page later on, or share it with others so they can easily find the same page. Your browser remembers your navigation history and allows you to navigate back and forth, too. This is called server-side routing.

      +## Things to consider when using frameworks -

      Modern web applications typically do not fetch and render new HTML files — they load a single HTML shell, and continually update the DOM inside it (referred to as single page apps, or SPAs) without navigating users to new addresses on the web. Each new pseudo-webpage is usually called a view, and by default, no routing is done.

      +Being an effective web developer means using the most appropriate tools for the job. JavaScript frameworks make front-end application development easy, but they are not a silver bullet that will solve all problems. This section talks about some of the things you should consider when using frameworks. Bear in mind that you might not need a framework at all — beware that you don't end up using a framework just for the sake of it. -

      When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in this fashion, it is aptly called client-side routing.

      +### Familiarity with the tool -

      It's possible to make a router using the native capabilities of JavaScript and the browser, but popular, actively developed frameworks have companion libraries that make routing a more intuitive part of the development process.

      +Just like vanilla JavaScript, frameworks take time to learn and have their quirks. Before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you, and be sure that your teammates are comfortable with it as well. -

      Things to consider when using frameworks

      +### Overengineering -

      Being an effective web developer means using the most appropriate tools for the job. JavaScript frameworks make front-end application development easy, but they are not a silver bullet that will solve all problems. This section talks about some of the things you should consider when using frameworks. Bear in mind that you might not need a framework at all — beware that you don't end up using a framework just for the sake of it.

      +If your web development project is a personal portfolio with a few pages, and those pages have little or no interactive capability, a framework (and all of its JavaScript) may not be necessary at all. That said, frameworks are not a monolith, and some of them are better-suited to small projects than others. In an article for Smashing Magazine, Sarah Drasner writes about how [Vue can replace jQuery](https://www.smashingmagazine.com/2018/02/jquery-vue-javascript/) as a tool for making small portions of a webpage interactive. -

      Familiarity with the tool

      +### Larger code base and abstraction -

      Just like vanilla JavaScript, frameworks take time to learn and have their quirks. Before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you, and be sure that your teammates are comfortable with it as well.

      +Frameworks allow you to write more declarative code – and sometimes _less_ code overall – by dealing with the DOM interactions for you, behind the scenes. This abstraction is great for your experience as a developer, but it isn't free. In order to translate what you write into DOM changes, frameworks have to run their own code, which in turn makes your final piece of software larger and more computationally expensive to operate. -

      Overengineering

      +Some extra code is inevitable, and a framework that supports tree-shaking (removal of any code that isn't actually used in the app during the build process) will allow you to keep your applications small, but this is still a factor you need to keep in mind when considering your app's performance, especially on more network/storage-constrained devices, like mobile phones. -

      If your web development project is a personal portfolio with a few pages, and those pages have little or no interactive capability, a framework (and all of its JavaScript) may not be necessary at all. That said, frameworks are not a monolith, and some of them are better-suited to small projects than others. In an article for Smashing Magazine, Sarah Drasner writes about how Vue can replace jQuery as a tool for making small portions of a webpage interactive.

      +The abstraction of frameworks affects not only your JavaScript, but your relationship with the very nature of the web. No matter how you build for the web, the end result, the layer that your users ultimately interact with, is HTML. Writing your whole application in JavaScript can make you lose sight of HTML and the purpose of its various tags, and lead you to produce an HTML document that is un-semantic and inaccessible. In fact, it's possible to write a fragile application that depends entirely on JavaScript and will not function without it. -

      Larger code base and abstraction

      +Frameworks are not the source of our problems. With the wrong priorities, it's possible for _any_ application to be fragile, bloated, and inaccessible. Frameworks do, however, amplify our priorities as developers. If your priority is to make a complex web app, it's easy to do that. However, if your priorities don't carefully guard performance and accessibility, frameworks will amplify your fragility, your bloat, and your inaccessibility. Modern developer priorities, amplified by frameworks, have inverted the structure of the web in many places. Instead of a robust, content-first network of documents, the web now often puts JavaScript first and user experience last. -

      Frameworks allow you to write more declarative code – and sometimes less code overall – by dealing with the DOM interactions for you, behind the scenes. This abstraction is great for your experience as a developer, but it isn't free. In order to translate what you write into DOM changes, frameworks have to run their own code, which in turn makes your final piece of software larger and more computationally expensive to operate.

      +## Accessibility on a framework-driven web -

      Some extra code is inevitable, and a framework that supports tree-shaking (removal of any code that isn't actually used in the app during the build process) will allow you to keep your applications small, but this is still a factor you need to keep in mind when considering your app's performance, especially on more network/storage-constrained devices, like mobile phones.

      +Let's build on what we said in the previous section, and talk a bit more about accessibility. Making user interfaces accessible always requires some thought and effort, and frameworks can complicate that process. You often have to employ advanced framework APIs to access native browser features like ARIA [live regions](/fr/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) or focus management. -

      The abstraction of frameworks affects not only your JavaScript, but your relationship with the very nature of the web. No matter how you build for the web, the end result, the layer that your users ultimately interact with, is HTML. Writing your whole application in JavaScript can make you lose sight of HTML and the purpose of its various tags, and lead you to produce an HTML document that is un-semantic and inaccessible. In fact, it's possible to write a fragile application that depends entirely on JavaScript and will not function without it.

      +In some cases, framework applications create accessibility barriers that do not exist for traditional websites. The biggest example of this is in client-side routing, as mentioned earlier. -

      Frameworks are not the source of our problems. With the wrong priorities, it's possible for any application to be fragile, bloated, and inaccessible. Frameworks do, however, amplify our priorities as developers. If your priority is to make a complex web app, it's easy to do that. However, if your priorities don't carefully guard performance and accessibility, frameworks will amplify your fragility, your bloat, and your inaccessibility. Modern developer priorities, amplified by frameworks, have inverted the structure of the web in many places. Instead of a robust, content-first network of documents, the web now often puts JavaScript first and user experience last.

      +With traditional (server-side) routing, navigating the web has predictable results. The browser knows to set focus to the top of the page and assistive technologies will announce the title of the page. These things happen every time you navigate to a new page. -

      Accessibility on a framework-driven web

      +With client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. Framework authors have devoted immense time and labor to writing JavaScript that recreates these features, and even then, no framework has done so perfectly. -

      Let's build on what we said in the previous section, and talk a bit more about accessibility. Making user interfaces accessible always requires some thought and effort, and frameworks can complicate that process. You often have to employ advanced framework APIs to access native browser features like ARIA live regions or focus management.

      +The upshot is that you should consider accessibility from the very start of _every_ web project, but bear in mind that abstracted codebases that use frameworks are more likely to suffer from major accessibility issues if you don't. -

      In some cases, framework applications create accessibility barriers that do not exist for traditional websites. The biggest example of this is in client-side routing, as mentioned earlier.

      +## How to choose a framework -

      With traditional (server-side) routing, navigating the web has predictable results. The browser knows to set focus to the top of the page and assistive technologies will announce the title of the page. These things happen every time you navigate to a new page.

      +Each of the frameworks discussed in this module take different approaches to web application development. Each is regularly improving or changing, and each has its pros and cons. Choosing the right framework is a team- and project-dependent process, and you should do your own research to uncover what suits your needs. That said, we've identified a few questions you can ask in order to research your options more effectively: -

      With client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. Framework authors have devoted immense time and labor to writing JavaScript that recreates these features, and even then, no framework has done so perfectly.

      +1. What browsers does the framework support? +2. What domain-specific languages does the framework utilize? +3. Does the framework have a strong community and good docs (and other support) available? -

      The upshot is that you should consider accessibility from the very start of every web project, but bear in mind that abstracted codebases that use frameworks are more likely to suffer from major accessibility issues if you don't.

      +The table in this section provides a glanceable summary of the current _browser support_ offered by each framework, as well as the **domain-specific languages** with which it can be used. -

      How to choose a framework

      +Broadly, domain-specific languages (**DSLs**) are programming languages relevant in specific areas of software development. In the context of frameworks, DSLs are variations on JavaScript or HTML that make it easier to develop with that framework. Crucially, none of the frameworks _require_ a developer to use a specific DSL, but they have almost all been designed with a specific DSL in mind. Choosing not to employ a framework’s preferred DSL will mean you miss out on features that would otherwise improve your developer experience. -

      Each of the frameworks discussed in this module take different approaches to web application development. Each is regularly improving or changing, and each has its pros and cons. Choosing the right framework is a team- and project-dependent process, and you should do your own research to uncover what suits your needs. That said, we've identified a few questions you can ask in order to research your options more effectively:

      +You should seriously consider the support matrix and DSLs of a framework when making a choice for any new project. Mismatched browser support can be a barrier to your users; mismatched DSL support can be a barrier to you and your teammates. -
        -
      1. What browsers does the framework support?
      2. -
      3. What domain-specific languages does the framework utilize?
      4. -
      5. Does the framework have a strong community and good docs (and other support) available?
      6. -
      +| Framework | Browser support | Preferred DSL | Supported DSLs | +| --------- | ----------------------------------- | ------------- | ---------------------- | +| Angular | IE9+ | TypeScript | HTML-based; TypeScript | +| React | Modern (IE9+ with Polyfills) | JSX | JSX; TypeScript | +| Vue | IE9+ | HTML-based | HTML-based, JSX, Pug | +| Ember | Modern (IE9+ in Ember version 2.18) | Handlebars | Handlebars, TypeScript | -

      The table in this section provides a glanceable summary of the current browser support offered by each framework, as well as the domain-specific languages with which it can be used.

      +> **Note :**: DSLs we've described as "HTML-based" do not have official names. They are not really true DSLs, but they are non-standard HTML, so we believe they are worth highlighting. -

      Broadly, domain-specific languages (DSLs) are programming languages relevant in specific areas of software development. In the context of frameworks, DSLs are variations on JavaScript or HTML that make it easier to develop with that framework. Crucially, none of the frameworks require a developer to use a specific DSL, but they have almost all been designed with a specific DSL in mind. Choosing not to employ a framework’s preferred DSL will mean you miss out on features that would otherwise improve your developer experience.

      +Citations for this table: -

      You should seriously consider the support matrix and DSLs of a framework when making a choice for any new project. Mismatched browser support can be a barrier to your users; mismatched DSL support can be a barrier to you and your teammates.

      +- [React browser support: official docs](https://reactjs.org/docs/react-dom.html#browser-support) +- [Ember browser support: Ember 3.0 release announcement](https://blog.emberjs.com/2018/02/14/ember-3-0-released.html) +- [Ember templating language (official docs)](https://guides.emberjs.com/v3.3.0/templates/handlebars-basics/) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      FrameworkBrowser supportPreferred DSLSupported DSLs
      AngularIE9+TypeScriptHTML-based; TypeScript
      ReactModern (IE9+ with Polyfills)JSXJSX; TypeScript
      VueIE9+HTML-basedHTML-based, JSX, Pug
      EmberModern (IE9+ in Ember version 2.18)HandlebarsHandlebars, TypeScript
      +### Does the framework have a strong community? -
      -

      Note :: DSLs we've described as "HTML-based" do not have official names. They are not really true DSLs, but they are non-standard HTML, so we believe they are worth highlighting.

      -
      +This is perhaps the hardest metric to measure, because community size does not correlate directly to easy-to-access numbers. You can check a project's number of GitHub stars or weekly npm downloads to get an idea of its popularity, but sometimes the best thing to do is search a few forums or talk to other developers. It is not just about the community's size, but also how welcoming and inclusive it is, and how good available documentation is. -

      Citations for this table:

      +### Opinions on the web - +Don't just take our word on this matter — there are discussions all over the web. The Wikimedia Foundation recently chose to use Vue for its front-end, and posted a [request for comments (RFC) on framework adoption](https://phabricator.wikimedia.org/T241180). Eric Gardner, the author of the RFC, took time to outline the needs of the Wikimedia project and why certain frameworks were good choices for the team. This RFC serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework. -

      Does the framework have a strong community?

      +The [State of JavaScript survey](https://stateofjs.com/) is a helpful collection of feedback from JavaScript developers. It covers many topics related to JavaScript, including data about both the use of frameworks and developer sentiment toward them. Currently, there are several years of data available, allowing you to get a sense of a framework's popularity. -

      This is perhaps the hardest metric to measure, because community size does not correlate directly to easy-to-access numbers. You can check a project's number of GitHub stars or weekly npm downloads to get an idea of its popularity, but sometimes the best thing to do is search a few forums or talk to other developers. It is not just about the community's size, but also how welcoming and inclusive it is, and how good available documentation is.

      +The Vue team has [exhaustively compared Vue to other popular frameworks](https://vuejs.org/v2/guide/comparison.html). There may be some bias in this comparison (which they note), but it's a valuable resource nonetheless. -

      Opinions on the web

      +## Alternatives to client-side frameworks -

      Don't just take our word on this matter — there are discussions all over the web. The Wikimedia Foundation recently chose to use Vue for its front-end, and posted a request for comments (RFC) on framework adoption. Eric Gardner, the author of the RFC, took time to outline the needs of the Wikimedia project and why certain frameworks were good choices for the team. This RFC serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework.

      +If you’re looking for tools to expedite the web development process, and you know your project isn’t going to require intensive client-side JavaScript, you could reach for one of a handful of other solutions for building the web: -

      The State of JavaScript survey is a helpful collection of feedback from JavaScript developers. It covers many topics related to JavaScript, including data about both the use of frameworks and developer sentiment toward them. Currently, there are several years of data available, allowing you to get a sense of a framework's popularity.

      +- A content management system +- Server-side rendering +- A static site generator -

      The Vue team has exhaustively compared Vue to other popular frameworks. There may be some bias in this comparison (which they note), but it's a valuable resource nonetheless.

      +### Content management systems -

      Alternatives to client-side frameworks

      +**Content-management systems** (**CMSes**) are any tools that allow a user to create content for the web without directly writing code themselves. They're a good solution for large projects, especially projects that require input from content writers who have limited coding ability, or for programmers who want to save time. They do, however, require a significant amount of time to set up, and utilizing a CMS means that you surrender at least some measure of control over the final output of your website. For example: if your chosen CMS doesn't author accessible content by default, it's often difficult to improve this. -

      If you’re looking for tools to expedite the web development process, and you know your project isn’t going to require intensive client-side JavaScript, you could reach for one of a handful of other solutions for building the web:

      +Popular examples include [Wordpress](https://wordpress.com/), [Joomla](https://www.joomla.org/), and [Drupal](https://www.drupal.org/). -
        -
      • A content management system
      • -
      • Server-side rendering
      • -
      • A static site generator
      • -
      +### Server-side rendering -

      Content management systems

      +**Server-side rendering** (**SSR**) is an application architecture in which it is the *server'*s job to render a single-page application. This is the opposite of _client-side rendering_, which is the most common and most straightforward way to build a JavaScript application. Server-side rendering is easier on the client's device, because you're only sending a rendered HTML file to them, but it can be difficult to set up compared to a client-side-rendered application. -

      Content-management systems (CMSes) are any tools that allow a user to create content for the web without directly writing code themselves. They're a good solution for large projects, especially projects that require input from content writers who have limited coding ability, or for programmers who want to save time. They do, however, require a significant amount of time to set up, and utilizing a CMS means that you surrender at least some measure of control over the final output of your website. For example: if your chosen CMS doesn't author accessible content by default, it's often difficult to improve this.

      +All of the frameworks covered in this module support server-side rendering as well as client-side rendering. Check out [Next.js](https://nextjs.org/) for React, [Nuxt.js](https://nuxtjs.org/) for Vue (yes it is confusing, and no, these projects are not related!), [FastBoot](https://github.com/ember-fastboot/ember-cli-fastboot) for Ember, and [Angular Universal](https://angular.io/guide/universal) for Angular. -

      Popular examples include Wordpress, Joomla, and Drupal.

      +> **Note :** Some SSR solutions are written and maintained by the community, whereas some are "official" solutions provided by the framework's maintainer. -

      Server-side rendering

      +### Static site generators -

      Server-side rendering (SSR) is an application architecture in which it is the server's job to render a single-page application. This is the opposite of client-side rendering, which is the most common and most straightforward way to build a JavaScript application. Server-side rendering is easier on the client's device, because you're only sending a rendered HTML file to them, but it can be difficult to set up compared to a client-side-rendered application.

      +Static site generators are programs that dynamically generate all the webpages of a multi-page website — including any relevant CSS or JavaScript — so that they can be published in any number of places. The publishing host could be a GitHub pages branch, a Netlify instance, or any private server of your choosing, for example. There are a number of advantages of this approach, mostly around performance (your user's device isn’t building the page with JavaScript; it's already complete) and security (static pages have fewer attack vectors). These sites can still utilize JavaScript where they need to, but they are not _dependent_ upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process. -

      All of the frameworks covered in this module support server-side rendering as well as client-side rendering. Check out Next.js for React, Nuxt.js for Vue (yes it is confusing, and no, these projects are not related!), FastBoot for Ember, and Angular Universal for Angular.

      +Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-side JavaScript applications, static site generators allow you a way to quickly create HTML files you would otherwise have written individually. Like frameworks, static site generators allow developers to write components that define common pieces of your web pages, and to compose those components together to create a final page. In the context of static site generators, these components are called **templates**. Web pages built by static site generators can even be home to framework applications: if you want one specific page of your statically-generated website to boot up a React application when your user visits it for example, you can do that. -
      -

      Note : Some SSR solutions are written and maintained by the community, whereas some are "official" solutions provided by the framework's maintainer.

      -
      +Static site generators have been around for quite a long time, but they have seen a bit of a revival in the recent history of the web. A handful of powerful options are now available, such as [Hugo](https://gohugo.io/), [Jekyll](https://jekyllrb.com/), [Eleventy](https://www.11ty.dev/), and [Gatsby](https://www.gatsbyjs.org/). -

      Static site generators

      +If you'd like to learn more about static site generators on the whole, check out Tatiana Mac's [Beginner's guide to Eleventy](https://tatianamac.com/posts/beginner-eleventy-tutorial-parti/). In the first article of the series, she explains what a static site generator is, and how it relates to other means of publishing web content. -

      Static site generators are programs that dynamically generate all the webpages of a multi-page website — including any relevant CSS or JavaScript — so that they can be published in any number of places. The publishing host could be a GitHub pages branch, a Netlify instance, or any private server of your choosing, for example. There are a number of advantages of this approach, mostly around performance (your user's device isn’t building the page with JavaScript; it's already complete) and security (static pages have fewer attack vectors). These sites can still utilize JavaScript where they need to, but they are not dependent upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process.

      +## Summary -

      Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-side JavaScript applications, static site generators allow you a way to quickly create HTML files you would otherwise have written individually. Like frameworks, static site generators allow developers to write components that define common pieces of your web pages, and to compose those components together to create a final page. In the context of static site generators, these components are called templates. Web pages built by static site generators can even be home to framework applications: if you want one specific page of your statically-generated website to boot up a React application when your user visits it for example, you can do that.

      +And that brings us to the end of our introduction to frameworks — we’ve not taught you any code yet, but hopefully we've given you a useful background on why you'd use frameworks in the first place and how to go about choosing one, and made you excited to learn more and get stuck in! -

      Static site generators have been around for quite a long time, but they have seen a bit of a revival in the recent history of the web. A handful of powerful options are now available, such as Hugo, Jekyll, Eleventy, and Gatsby.

      +Our next article goes down to a lower level, looking at the specific kinds of features frameworks tend to offer, and why they work like they do. -

      If you'd like to learn more about static site generators on the whole, check out Tatiana Mac's Beginner's guide to Eleventy. In the first article of the series, she explains what a static site generator is, and how it relates to other means of publishing web content.

      +{{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -

      Summary

      +## In this module -

      And that brings us to the end of our introduction to frameworks — we’ve not taught you any code yet, but hopefully we've given you a useful background on why you'd use frameworks in the first place and how to go about choosing one, and made you excited to learn more and get stuck in!

      +- [Introduction to client-side frameworks](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) +- [Framework main features](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) +- React -

      Our next article goes down to a lower level, looking at the specific kinds of features frameworks tend to offer, and why they work like they do.

      + - [Getting started with React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - [Beginning our React todo list](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - [Componentizing our React app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - [React interactivity: Events and state](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - [React interactivity: Editing, filtering, conditional rendering](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - [Accessibility in React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - [React resources](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) -

      {{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

      +- Ember -

      In this module

      + - [Getting started with Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - [Ember app structure and componentization](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - [Ember interactivity: Events, classes and state](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - [Ember Interactivity: Footer functionality, conditional rendering](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - [Routing in Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - [Ember resources and troubleshooting](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) - +- Vue + + - [Getting started with Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - [Creating our first Vue component](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - [Rendering a list of Vue components](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - [Adding a new todo form: Vue events, methods, and models](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - [Styling Vue components with CSS](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - [Using Vue computed properties](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - [Vue conditional rendering: editing existing todos](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - [Focus management with Vue refs](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - [Vue resources](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + +- Svelte + + - [Getting started with Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - [Starting our Svelte Todo list app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - [Dynamic behavior in Svelte: working with variables and props](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - [Componentizing our Svelte app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - [Advanced Svelte: Reactivity, lifecycle, accessibility](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - [Working with Svelte stores](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - [TypeScript support in Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - [Deployment and next steps](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) diff --git a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md index 4b4edd429a..c51043feed 100644 --- a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md +++ b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md @@ -3,278 +3,315 @@ title: Fonctionnalités principales des framework slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features translation_of: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features --- -
      {{LearnSidebar}}
      +{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
      {{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
      - -

      Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level, and the differences between them.

      +Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of “the big 4” frameworks, looking at how frameworks tend to work from a high level, and the differences between them. - - - - - - - - - - + + + + + + + + + +
      Prerequisites:Familiarity with the core HTML, CSS, and JavaScript languages.
      Objective:To understand the main code features of frameworks.
      Prerequisites: + Familiarity with the core HTML, + CSS, and + JavaScript languages. +
      Objective:To understand the main code features of frameworks.
      -

      Domain-specific languages

      +## Domain-specific languages -

      All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of JSX for writing its components, while Ember utilizes Handlebars. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.

      +All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of **JSX** for writing its components, while Ember utilizes **Handlebars**. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI. -

      Angular apps often make heavy use of TypeScript. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript.

      +Angular apps often make heavy use of **TypeScript**. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript. -

      DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.

      +DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. [Transformation is an extra step in the development process](/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview#Transformation), but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks. -

      JSX

      +### JSX -

      JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance.

      +[JSX](https://reactjs.org/docs/introducing-jsx.html), which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications — like Vue apps, for instance. -

      The following shows a simple JSX example:

      +The following shows a simple JSX example: -
      const subject = "World";
      +```js
      +const subject = "World";
       const header = (
      -  <header>
      -    <h1>Hello, {subject}!</h1>
      -  </header>
      -);
      +
      +

      Hello, {subject}!

      +
      +); +``` -

      This expression represents an HTML <header> element with a <h1> element inside. The curly braces around subject on line 4 tell the application to read the value of the subject constant and insert it into our <h1>.

      +This expression represents an HTML [`
      `](/fr/docs/Web/HTML/Element/header) element with a [`

      `](/fr/docs/Web/HTML/Element/Heading_Elements) element inside. The curly braces around `subject` on line 4 tell the application to read the value of the `subject` constant and insert it into our `

      `. -

      When used with React, the JSX from the previous snippet would be compiled into this:

      +When used with React, the JSX from the previous snippet would be compiled into this: -
      var subject = "World";
      +```js
      +var subject = "World";
       var header = React.createElement("header", null,
         React.createElement("h1", null, "Hello, ", subject, "!")
      -);
      +); +``` -

      When ultimately rendered by the browser, the above snippet will produce HTML that looks like this:

      +When ultimately rendered by the browser, the above snippet will produce HTML that looks like this: -
      <header>
      -  <h1>Hello, World!</h1>
      -</header>
      +```html +
      +

      Hello, World!

      +
      +``` -

      Handlebars

      +### Handlebars -

      The Handlebars templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds.

      +The [Handlebars](https://handlebarsjs.com/) templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds. -

      Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair.

      +Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair. -

      Given this Handlebars template:

      +Given this Handlebars template: -
      <header>
      -  <h1>Hello, \{{subject}}!</h1>
      -</header>
      +```html +
      +

      Hello, \{{subject}}!

      +
      +``` -

      And this data:

      +And this data: -
      {
      +```js
      +{
         subject: "World"
      -}
      +} +``` -

      Handlebars will build HTML like this:

      +Handlebars will build HTML like this: -
      <header>
      -  <h1>Hello, World!</h1>
      -</header>
      +```html +
      +

      Hello, World!

      +
      +``` -

      TypeScript

      +### TypeScript -

      TypeScript is a superset of JavaScript, meaning it extends JavaScript — all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function add(), which takes integers a and b and returns their sum.

      +[TypeScript](https://www.typescriptlang.org/) is a _superset_ of JavaScript, meaning it extends JavaScript — all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function `add()`, which takes integers `a` and `b` and returns their sum. -

      In JavaScript, that function could be written like this:

      +In JavaScript, that function could be written like this: -
      function add(a, b) {
      +```js
      +function add(a, b) {
         return a + b;
      -}
      +} +``` -

      This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings — it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible:

      +This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the `+` operator to concatenate strings together, so this function would technically still work if `a` and `b` were strings — it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible: -
      function add(a: number, b: number) {
      +```js
      +function add(a: number, b: number) {
         return a + b;
      -}
      +} +``` -

      The : number written after each parameter here tells TypeScript that both a and b must be numbers. If we were to use this function and pass '2' into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us.

      +The `: number` written after each parameter here tells TypeScript that both `a` and `b` must be numbers. If we were to use this function and pass `'2'` into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us. -

      Writing components

      +## Writing components -

      As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML.

      +As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML. -

      Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.

      +Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup. -

      The code snippets in the rest of this section will use React as an example, and are written with JSX.

      +The code snippets in the rest of this section will use React as an example, and are written with JSX. -

      Properties

      +### Properties -

      Properties, or props, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an AuthorCredit component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, AuthorCredit needs to accept some props.

      +Properties, or **props**, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an `AuthorCredit` component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, `AuthorCredit` needs to accept some props. -

      A React representation of this AuthorCredit component might look something like this:

      +A React representation of this `AuthorCredit` component might look something like this: -
      function AuthorCredit(props) {
      +```js
      +function AuthorCredit(props) {
         return (
      -    <figure>
      -      <img src={props.src} alt={props.alt} />
      -      <figcaption>{props.byline}</figcaption>
      -    </figure>
      +    
      + {props.alt} +
      {props.byline}
      +
      ); -}
      +} +``` -

      {props.src}, {props.alt}, and {props.byline} represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component):

      +`{props.src}`, `{props.alt}`, and `{props.byline}` represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component): -
      <AuthorCredit
      +```js
      +
      +/>
      +```
       
      -

      This will ultimately render the following <figure> element in the browser, with its structure as defined in the AuthorCredit component, and its content as defined in the props included on the AuthorCredit component call:

      +This will ultimately render the following [`
      `](/fr/docs/Web/HTML/Element/figure) element in the browser, with its structure as defined in the `AuthorCredit` component, and its content as defined in the props included on the `AuthorCredit` component call: -
      <figure>
      -  <img
      +```html
      +
      + Portrait of Zelda Schiff +
      Zelda Schiff is editor-in-chief of the Library Times. - </figcaption> -</figure>
      + +
      +``` -

      State

      +### State -

      We talked about the concept of state in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.

      +We talked about the concept of **state** in the previous chapter — a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered. -

      As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own count state, and could be written like this:

      +As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own _count_ state, and could be written like this: -
      function CounterButton() {
      +```js
      +function CounterButton() {
         const [count] = useState(0);
         return (
      -    <button>Clicked {count} times</button>
      +    
         );
      -}
      +} +``` -

      useState() is a React hook which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser:

      +[`useState()`](https://reactjs.org/docs/hooks-reference.html#usestate) is a **[React hook](https://reactjs.org/docs/hooks-intro.html)** which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser: -
      <button>Clicked 0 times</button>
      +```html + +``` -

      The useState() call keeps track of the count value in a robust way across the app, without you needing to write code to do that yourself.

      +The `useState()` call keeps track of the `count` value in a robust way across the app, without you needing to write code to do that yourself. -

      Events

      +### Events -

      In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.

      +In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events. -

      In React, listening for the click event requires a special property, onClick. Let’s update our CounterButton code from above to allow it to count clicks:

      +In React, listening for the [`click`](/fr/docs/Web/API/Element/click_event) event requires a special property, `onClick`. Let’s update our `CounterButton` code from above to allow it to count clicks: -
      function CounterButton() {
      +```js
      +function CounterButton() {
         const [count, setCount] = useState(0);
         return (
      -    <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
      +    
         );
      -}
      +} +``` -

      In this version we are using additional useState() functionality to create a special setCount() function, which we can invoke to update the value of count. We call this function on line 4, and set count to whatever its current value is, plus one.

      +In this version we are using additional `useState()` functionality to create a special `setCount()` function, which we can invoke to update the value of `count`. We call this function on line 4, and set `count` to whatever its current value is, plus one. -

      Styling components

      +## Styling components -

      Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS.

      +Each framework offers a way to define styles for your components — or for the application as a whole. Although each framework’s approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in [Sass](https://sass-lang.com/) or [Less](http://lesscss.org/), or transpile your CSS stylesheets with [PostCSS](https://postcss.org/). -

      Handling dependencies

      +## Handling dependencies -

      All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard JavaScript module syntax, or at least something similar.

      +All major frameworks provide mechanisms for handling dependencies — using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard [JavaScript module syntax](/fr/docs/Web/JavaScript/Guide/Modules), or at least something similar. -

      Components in components

      +### Components in components -

      One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components.

      +One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components. -

      For example, our AuthorCredit React component might be utilized inside an Article component. That means that Article would need to import AuthorCredit.

      +For example, our `AuthorCredit` React component might be utilized inside an `Article` component. That means that `Article` would need to import `AuthorCredit`. -
      import AuthorCredit from "./components/AuthorCredit";
      +```js +import AuthorCredit from "./components/AuthorCredit"; +``` -

      Once that’s done, AuthorCredit could be used inside the Article component like this:

      +Once that’s done, `AuthorCredit` could be used inside the `Article` component like this: -
        ...
      +```js
      +  ...
       
      -<AuthorCredit />
      +
       
      -  ...
      + ... +``` -

      Dependency injection

      +### Dependency injection -

      Real-world applications can often involve component structures with multiple levels of nesting. An AuthorCredit component nested many levels deep might, for some reason, need data from the very root level of our application.

      +Real-world applications can often involve component structures with multiple levels of nesting. An `AuthorCredit` component nested many levels deep might, for some reason, need data from the very root level of our application. -

      Let's say that the magazine site we're building is structured like this:

      +Let's say that the magazine site we're building is structured like this: -
      <App>
      -  <Home>
      -    <Article>
      -      <AuthorCredit {/* props */} />
      -    </Article>
      -  </Home>
      -</App>
      +```js + + +
      + +
      +
      +
      +``` -

      Our App component has data that our AuthorCredit component needs. We could rewrite Home and Article so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: Home and Article don’t actually make use of the author's portrait or byline, but if we want to get that information into the AuthorCredit, we will need to change Home and Author to accommodate it.

      +Our `App` component has data that our `AuthorCredit` component needs. We could rewrite `Home` and `Article` so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: `Home` and `Article` don’t actually make use of the author's portrait or byline, but if we want to get that information into the `AuthorCredit`, we will need to change `Home` and `Author` to accommodate it. -

      The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications.

      +The problem of passing data through many layers of components is called prop drilling, and it’s not ideal for large applications. -

      To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.

      +To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same. -

      Angular calls this process dependency injection; Vue has provide() and inject() component methods; React has a Context API; Ember shares state through services.

      +Angular calls this process [dependency injection](https://angular.io/guide/dependency-injection); Vue has [`provide()` and `inject()` component methods](https://vuejs.org/v2/api/#provide-inject); React has a [Context API](https://reactjs.org/docs/context.html); Ember shares state through [services](https://guides.emberjs.com/release/services/). -

      Lifecycle

      +### Lifecycle -

      In the context of a framework, a component’s lifecycle is a collection of phases a component goes through from the time it is rendered by the browser (often called mounting) to the time that it is removed from the DOM (often called unmounting). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component mounts, when it renders, when it unmounts, and at many phases in between these.

      +In the context of a framework, a component’s **lifecycle** is a collection of phases a component goes through from the time it is rendered by the browser (often called _mounting_) to the time that it is removed from the DOM (often called _unmounting_). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component _mounts_, when it _renders_, when it _unmounts_, and at many phases in between these. -

      The render phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there.

      +The _render_ phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what’s there. -

      This diagram of a React component's lifecycle offers a general overview of the concept.

      +This [diagram of a React component's lifecycle](http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) offers a general overview of the concept. -

      Rendering elements

      +## Rendering elements -

      Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for.

      +Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they’re known for. -

      The Virtual DOM is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.

      +The **Virtual DOM** is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM — the DOM that is actually rendered for your users — in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering. -

      You can read more about the Virtual DOM in the React docs.

      +You can [read more about the Virtual DOM in the React docs](https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom). -

      The Incremental DOM is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM.

      +The **Incremental DOM** is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM. -

      You can read more about the Incremental DOM on the Auth0 blog.

      +You can [read more about the Incremental DOM on the Auth0 blog](https://auth0.com/blog/incremental-dom/). -

      The Glimmer VM is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript.

      +The **Glimmer VM** is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript. -

      Routing

      +## Routing -

      As mentioned in the previous chapter, routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.

      +As [mentioned in the previous chapter, routing](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction#Routing) is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications. -

      Testing

      +## Testing -

      All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.

      +All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools. -

      Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.

      +Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike. -

      Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular.  The Ember docs cover the testing of Ember apps.

      +[Testing Library](https://testing-library.com/) is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular.  The Ember docs cover the [testing of Ember apps](https://guides.emberjs.com/release/testing/). -

      Here’s a quick test for our CounterButton written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:

      +Here’s a quick test for our `CounterButton` written with the help of React Testing Library — it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times: -
      import React from "react";
      +```js
      +import React from "react";
       import { render, fireEvent } from "@testing-library/react";
       import "@testing-library/jest-dom/extend-expect";
       
       import CounterButton from "./CounterButton";
       
      -it("renders a semantic with an initial state of 0", () => {
      -  const { getByRole } = render(<CounterButton />);
      +it("renders a semantic with an initial state of 0", () => {
      +  const { getByRole } = render();
         const btn = getByRole("button");
       
         expect(btn).toBeInTheDocument();
         expect(btn).toHaveTextContent("Clicked 0 times");
       });
       
      -it("Increments the count when clicked", () => {
      -  const { getByRole } = render(<CounterButton />);
      +it("Increments the count when clicked", () => {
      +  const { getByRole } = render();
         const btn = getByRole("button");
       
         fireEvent.click(btn);
      @@ -282,73 +319,63 @@ it("Increments the count when clicked", () => {
       
         fireEvent.click(btn);
         expect(btn).toHaveTextContent("Clicked 2 times");
      -});
      - -

      Summary

      - -

      At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first:

      - - - -
      -

      Note : We only have three framework tutorial series available now, but we hope to have more available in the future.

      -
      - -

      {{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}

      - -

      In this module

      - - +}); +``` + +## Summary + +At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you’re enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first: + +- [React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) +- [Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) +- [Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + +> **Note :** We only have three framework tutorial series available now, but we hope to have more available in the future. + +{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} + +## In this module + +- [Introduction to client-side frameworks](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction) +- [Framework main features](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features) +- React + + - [Getting started with React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started) + - [Beginning our React todo list](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning) + - [Componentizing our React app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components) + - [React interactivity: Events and state](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state) + - [React interactivity: Editing, filtering, conditional rendering](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering) + - [Accessibility in React](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility) + - [React resources](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources) + +- Ember + + - [Getting started with Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started) + - [Ember app structure and componentization](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization) + - [Ember interactivity: Events, classes and state](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state) + - [Ember Interactivity: Footer functionality, conditional rendering](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer) + - [Routing in Ember](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing) + - [Ember resources and troubleshooting](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources) + +- Vue + + - [Getting started with Vue](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started) + - [Creating our first Vue component](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component) + - [Rendering a list of Vue components](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists) + - [Adding a new todo form: Vue events, methods, and models](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models) + - [Styling Vue components with CSS](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling) + - [Using Vue computed properties](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) + - [Vue conditional rendering: editing existing todos](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering) + - [Focus management with Vue refs](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management) + - [Vue resources](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources) + +- Svelte + + - [Getting started with Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started) + - [Starting our Svelte Todo list app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning) + - [Dynamic behavior in Svelte: working with variables and props](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props) + - [Componentizing our Svelte app](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components) + - [Advanced Svelte: Reactivity, lifecycle, accessibility](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility) + - [Working with Svelte stores](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores) + - [TypeScript support in Svelte](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript) + - [Deployment and next steps](/fr/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next) diff --git a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md index ff22108290..d658e99886 100644 --- a/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md +++ b/files/fr/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md @@ -13,456 +13,490 @@ tags: translation_of: >- Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started --- -
      {{LearnSidebar}}
      +{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}} -
      {{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
      - -

      In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process.

      +In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app, learning a bit about how React works in the process. - - - - - - - - - - + + + + + + + + + +
      Prerequisites: -

      Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line.

      - -

      React uses an HTML-in-JavaScript syntax called JSX (JavaScript and XML). Familiarity with both HTML and JavaScript will help you to learn JSX, and better identify whether bugs in your application are related to JavaScript or to the more specific domain of React.

      -
      Objective:To setup a local React development environment, create a start app, and understand the basics of how it works
      Prerequisites: +

      + Familiarity with the core HTML, + CSS, and + JavaScript languages, + knowledge of the + terminal/command line. +

      +

      + React uses an HTML-in-JavaScript syntax called JSX (JavaScript and + XML). Familiarity with both HTML and JavaScript will help you to learn + JSX, and better identify whether bugs in your application are related + to JavaScript or to the more specific domain of React. +

      +
      Objective: + To setup a local React development environment, create a start app, and + understand the basics of how it works +
      -

      Hello React

      - -

      As its official tagline states, React is a library for building user interfaces. React is not a framework – it's not even exclusive to the web. It's used with other libraries to render to certain environments. For instance, React Native can be used to build mobile applications; React 360 can be used to build virtual reality applications; and there are other possibilities besides.

      +## Hello React -

      To build for the web, developers use React in tandem with ReactDOM. React and ReactDOM are often discussed in the same spaces as, and utilized to solve the same problems as, other true web development frameworks. When we refer to React as a "framework", we’re working with that colloquial understanding.

      +As its official tagline states, [React](https://reactjs.org/) is a library for building user interfaces. React is not a framework – it's not even exclusive to the web. It's used with other libraries to render to certain environments. For instance, [React Native](https://reactnative.dev/) can be used to build mobile applications; [React 360](https://facebook.github.io/react-360/) can be used to build virtual reality applications; and there are other possibilities besides. -

      React's primary goal is to minimize the bugs that occur when developers are building UIs. It does this through the use of components — self-contained, logical pieces of code that describe a portion of the user interface. These components can be composed together to create a full UI, and React abstracts away much of the rendering work, leaving you to concentrate on the UI design.

      +To build for the web, developers use React in tandem with [ReactDOM](https://reactjs.org/docs/react-dom.html). React and ReactDOM are often discussed in the same spaces as, and utilized to solve the same problems as, other true web development frameworks. When we refer to React as a "framework", we’re working with that colloquial understanding. -

      Use cases

      +React's primary goal is to minimize the bugs that occur when developers are building UIs. It does this through the use of components — self-contained, logical pieces of code that describe a portion of the user interface. These components can be composed together to create a full UI, and React abstracts away much of the rendering work, leaving you to concentrate on the UI design. -

      Unlike the other frameworks covered in this module, React does not enforce strict rules around code conventions or file organization. This allows teams to set conventions that work best for them, and to adopt React in any way they would like to. React can handle a single button, a few pieces of an interface, or an app's entire user interface.

      +## Use cases -

      While React can be used for small pieces of an interface, it's not as easy to "drop into" an application as a library like jQuery, or even a framework like Vue — it is more approachable when you build your entire app with React.

      +Unlike the other frameworks covered in this module, React does not enforce strict rules around code conventions or file organization. This allows teams to set conventions that work best for them, and to adopt React in any way they would like to. React can handle a single button, a few pieces of an interface, or an app's entire user interface. -

      In addition, many of the developer-experience benefits of a React app, such as writing interfaces with JSX, require a compilation process. Adding a compiler like Babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. React arguably has a heavy tooling requirement, but it can be learnt.

      +While React _can_ be used for [small pieces of an interface](https://reactjs.org/docs/add-react-to-a-website.html), it's not as easy to "drop into" an application as a library like jQuery, or even a framework like Vue — it is more approachable when you build your entire app with React. -

      This article is going to focus on the use case of using React to render the entire user interface of an application, using tooling provided by Facebook’s own create-react-app tool.

      +In addition, many of the developer-experience benefits of a React app, such as writing interfaces with JSX, require a compilation process. Adding a compiler like Babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. React arguably has a heavy tooling requirement, but it can be learnt. -

      How does React use JavaScript?

      +This article is going to focus on the use case of using React to render the entire user interface of an application, using tooling provided by Facebook’s own [create-react-app](https://create-react-app.dev/) tool. -

      React utilizes features of modern JavaScript for many of its patterns. Its biggest departure from JavaScript comes with the use of JSX syntax. JSX extends JavaScript's syntax so that HTML-like code can live alongside it. For example:

      +## How does React use JavaScript? -
      const heading = <h1>Mozilla Developer Network</h1>;
      +React utilizes features of modern JavaScript for many of its patterns. Its biggest departure from JavaScript comes with the use of [JSX](https://reactjs.org/docs/introducing-jsx.html) syntax. JSX extends JavaScript's syntax so that HTML-like code can live alongside it. For example: -

      This heading constant is known as a JSX expression. React can use it to render that <h1> tag in our app.

      +```js +const heading =

      Mozilla Developer Network

      ; +``` -

      Suppose we wanted to wrap our heading in a <header> tag, for semantic reasons? The JSX approach allows us to nest our elements within each other, just like we do with HTML:

      +This heading constant is known as a **JSX expression**. React can use it to render that [`

      `](/fr/docs/Web/HTML/Element/Heading_Elements) tag in our app. -
      const header = (
      -  <header>
      -    <h1>Mozilla Developer Network</h1>
      -  </header>
      -);
      +Suppose we wanted to wrap our heading in a [`
      `](/fr/docs/Web/HTML/Element/header) tag, for semantic reasons? The JSX approach allows us to nest our elements within each other, just like we do with HTML: -
      -

      Note : The parentheses in the previous snippet aren't unique to JSX, and don’t have any effect on your application. They're a signal to you (and your computer) that the multiple lines of code inside are part of the same expression. You could just as well write the header expression like this:

      +```js +const header = ( +
      +

      Mozilla Developer Network

      +
      +); +``` -
      const header = <header>
      -    <h1>Mozilla Developer Network</h1>
      -</header>
      +> **Note :** The parentheses in the previous snippet aren't unique to JSX, and don’t have any effect on your application. They're a signal to you (and your computer) that the multiple lines of code inside are part of the same expression. You could just as well write the header expression like this: +> +> ```js +> const header =
      +>

      Mozilla Developer Network

      +>
      +> ``` +> +> However, this looks kind of awkward, because the [`
      `](/fr/docs/Web/HTML/Element/header) tag that starts the expression is not indented to the same position as its corresponding closing tag. -

      However, this looks kind of awkward, because the <header> tag that starts the expression is not indented to the same position as its corresponding closing tag.

      -
      +Of course, your browser can't read JSX without help. When compiled (using a tool like [Babel](https://babeljs.io/) or [Parcel](https://parceljs.org/)), our header expression would look like this: -

      Of course, your browser can't read JSX without help. When compiled (using a tool like Babel or Parcel), our header expression would look like this:

      - -
      const header = React.createElement("header", null,
      +```js
      +const header = React.createElement("header", null,
         React.createElement("h1", null, "Mozilla Developer Network")
      -);
      - -

      It's possible to skip the compilation step and use React.createElement() to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, popular tooling makes JSX-to-JavaScript compilation part of its setup process. You don't have to configure compilation yourself unless you want to.

      +); +``` -

      Because JSX is a blend of HTML and JavaScript, some developers find it intuitive. Others say that its blended nature makes it confusing. Once you're comfortable with it, however, it will allow you build user interfaces more quickly and intuitively, and allow others to better understand your code base at a glance.

      +It's _possible_ to skip the compilation step and use [`React.createElement()`](https://reactjs.org/docs/react-api.html#createelement) to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, popular tooling makes JSX-to-JavaScript compilation part of its setup process. You don't have to configure compilation yourself unless you want to. -

      To read more about JSX, check out the React team's JSX In Depth article.

      +Because JSX is a blend of HTML and JavaScript, some developers find it intuitive. Others say that its blended nature makes it confusing. Once you're comfortable with it, however, it will allow you build user interfaces more quickly and intuitively, and allow others to better understand your code base at a glance. -

      Setting up your first React app

      +To read more about JSX, check out the React team's [JSX In Depth](https://reactjs.org/docs/jsx-in-depth.html) article. -

      There are many ways to use React, but we're going to use the command-line interface (CLI) tool create-react-app, as mentioned earlier, which expedites the process of developing a React application by installing some packages and creating some files for you, handling the tooling described above.

      +## Setting up your first React app -

      It's possible to add React to a website without create-react-app by copying some <script> elements into an HTML file, but the create-react-app CLI is a common starting point for React applications. Using it will allow you spend more time building your app, and less time fussing with setup.

      +There are many ways to use React, but we're going to use the command-line interface (CLI) tool create-react-app, as mentioned earlier, which expedites the process of developing a React application by installing some packages and creating some files for you, handling the tooling described above. -

      Requirements

      +It's possible to [add React to a website without create-react-app](https://reactjs.org/docs/add-react-to-a-website.html) by copying some [` + ``` -
      <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
      -

    • -
    +- Production Script (Optimized version, minimal console warnings. It is recommended that you specify a version number when including Vue on your site so that any framework updates do not break your live site without you knowing.) -

    However, this approach has some limitations. To build more complex apps, you’ll want to use the Vue NPM package. This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:

    + ```html + + ``` -
      -
    1. Node.js 8.11+ installed.
    2. -
    3. npm or yarn.
    4. -
    +However, this approach has some limitations. To build more complex apps, you’ll want to use the [Vue NPM package](https://www.npmjs.com/package/vue). This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need: -
    -

    Note : If you don't have the above installed, find out more about installing npm and Node.js here.

    -
    +1. Node.js 8.11+ installed. +2. npm or yarn. -

    To install the CLI, run the following command in your terminal:

    +> **Note :** If you don't have the above installed, find out [more about installing npm and Node.js](/fr/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#Adding_powerups) here. -
    npm install --global @vue/cli
    +To install the CLI, run the following command in your terminal: -

    Or if you'd prefer to use yarn:

    +```bash +npm install --global @vue/cli +``` -
    yarn global add @vue/cli
    +Or if you'd prefer to use yarn: -

    Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run . The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.vue create <project-name>

    +```bash +yarn global add @vue/cli +``` -

    We’ll look at using this below.

    +Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run . The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.`vue create ` -

    Initializing a new project

    +We’ll look at using this below. -

    To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into. Follow the steps below:

    +## Initializing a new project -
      -
    1. In terminal, to where you'd like to create your sample app, then run .cdvue create moz-todo-vue
    2. -
    3. Use the arrow keys and to select the "Manually select features" option.Enter
    4. -
    5. The first menu you’ll be presented with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press to proceed.Enter
    6. -
    7. Next you’ll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit again. This will help us catch common errors, but not be overly opinionated.Enter
    8. -
    9. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit to continue.Enter
    10. -
    11. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's file. Select "In dedicated config files" and push .package.jsonEnter
    12. -
    13. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type , otherwise type .yn
    14. -
    +To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into. Follow the steps below: -

    The CLI will now begin scaffolding out your project, and installing all of your dependencies.

    +1. In terminal, to where you'd like to create your sample app, then run .` cd``vue create moz-todo-vue ` +2. Use the arrow keys and to select the "Manually select features" option. -

    If you've never run the Vue CLI before, you'll get one more question — you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag , when you run .  So if you wanted to create the project with npm and you'd previously chosen yarn, you’d run .--packageManager=<package-manager>vue createmoz-todo-vuevue create moz-todo-vue --packageManager=npm

    + Enter -
    -

    Note : We've not gone over all of the options here, but you can find more information on the CLI in the Vue docs.

    -
    +3. The first menu you’ll be presented with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press to proceed. -

    Project structure

    + Enter -

    If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:

    +4. Next you’ll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit again. This will help us catch common errors, but not be overly opinionated. -
      -
    • .eslintrc.js: This is a config file for eslint. You can use this to manage your linting rules.
    • -
    • babel.config.js: This is the config file for Babel, which transforms modern JavaScript features being used in development code into older syntax that is more cross-browser compatible in production code. You can register additional babel plugins in this file.
    • -
    • .browserslistrc: This is a config for Browserslist. You can use this to control which browsers your tooling optimizes for.
    • -
    • public: This directory contains static assets that are published, but not processed by Webpack during build (with one exception; gets some processing).index.html -
        -
      • favicon.ico: This is the favicon for your app. Currently, it's the Vue logo.
      • -
      • index.html: This is the template for your app. Your Vue app is run from this HTML page, and you can use lodash template syntax to interpolate values into it. -
        -

        Note : this is not the template for managing the layout of your application — this template is for managing static HTML that sits outside of your Vue app. Editing this file typically only occurs in advanced use cases.

        -
      • -
      -
    • -
    • src: This directory contains the core of your Vue app. -
        -
      • main.js: this is the entry point to your application. Currently, this file initializes your Vue application and signifies which HTML element in the file your app should be attached to. This file is often where you register global components or additional Vue libraries.index.html
      • -
      • App.vue: this is the top-level component in your Vue app. See below for more explanation of Vue components.
      • -
      • components: this directory is where you keep your components. Currently it just has one example component.
      • -
      • assets: This directory is for storing static assets like CSS and images. Because these files are in the source directory, they can be processed by Webpack. This means you can use pre-processors like Sass/SCSS or Stylus.
      • -
      -
    • -
    + Enter -
    -

    Note : Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a directory).views

    -
    +5. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit to continue. -

    .vue files (single file components)

    + Enter -

    Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.

    +6. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their own, dedicated files. The other option, "In package.json", will put all of your config settings into the app's file. Select "In dedicated config files" and push .`package.json` -

    While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using Single File Components, Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in . These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components..vue

    + Enter -

    As a bonus, projects created with the Vue CLI are configured to use files with Webpack out of the box. In fact, if you look inside the folder in the project we created with the CLI, you'll see your first file: ..vuesrc.vueApp.vue

    +7. Finally, you are asked if you want to save this as a preset for future options. This is entirely up to you. If you like these settings over the existing presets and want to use them again, type , otherwise type . -

    Let's explore this now.

    + y -

    App.vue

    + n -

    Open your file — you’ll see that it has three parts: , , and , which contain the component’s template, scripting, and styling information. All Single File Components share this same basic structure.App.vue<template><script><style>

    +The CLI will now begin scaffolding out your project, and installing all of your dependencies. -

    <template> contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.

    +If you've never run the Vue CLI before, you'll get one more question — you'll be asked to choose a package manager. You can use the arrow keys to select which one you prefer. The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag , when you run .  So if you wanted to create the project with npm and you'd previously chosen yarn, you’d run .` --packageManager=``vue create``moz-todo-vue``vue create moz-todo-vue --packageManager=npm ` -
    -

    Note : By setting the attribute on the tag, you can use Pug template syntax instead of standard HTML — . We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.lang<template><template lang="pug">

    -
    +> **Note :** We've not gone over all of the options here, but you can [find more information on the CLI](https://cli.vuejs.org) in the Vue docs. -

    <script> contains all of the non-display logic of your component. Most importantly, your tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a function.<script>render()

    +## Project structure -

    In the case of , our default export sets the name of the component to and registers the component by adding it into the property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.App.vueappHelloWorldcomponents

    +If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows: -
    import HelloWorld from './components/HelloWorld.vue';
    +- `.eslintrc.js`: This is a config file for [eslint](https://eslint.org/). You can use this to manage your linting rules.
    +- `babel.config.js`: This is the config file for [Babel](https://babeljs.io/), which transforms modern JavaScript features being used in development code into older syntax that is more cross-browser compatible in production code. You can register additional babel plugins in this file.
    +- `.browserslistrc`: This is a config for [Browserslist](https://github.com/browserslist/browserslist). You can use this to control which browsers your tooling optimizes for.
    +- `public`: This directory contains static assets that are published, but not processed by [Webpack](https://webpack.js.org/) during build (with one exception; gets some processing).`index.html`
    +
    +  - `favicon.ico`: This is the favicon for your app. Currently, it's the Vue logo.
    +  - `index.html`: This is the template for your app. Your Vue app is run from this HTML page, and you can use lodash template syntax to interpolate values into it.
    +
    +    > **Note :** this is not the template for managing the layout of your application — this template is for managing static HTML that sits outside of your Vue app. Editing this file typically only occurs in advanced use cases.
    +
    +- `src`: This directory contains the core of your Vue app.
    +
    +  - `main.js`: this is the entry point to your application. Currently, this file initializes your Vue application and signifies which HTML element in the file your app should be attached to. This file is often where you register global components or additional Vue libraries.`index.html`
    +  - `App.vue`: this is the top-level component in your Vue app. See below for more explanation of Vue components.
    +  - `components`: this directory is where you keep your components. Currently it just has one example component.
    +  - `assets`: This directory is for storing static assets like CSS and images. Because these files are in the source directory, they can be processed by Webpack. This means you can use pre-processors like [Sass/SCSS](https://sass-lang.com/) or [Stylus](https://stylus-lang.com/).
    +
    +> **Note :** Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a directory).`views`
    +
    +## .vue files (single file components)
    +
    +Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.
    +
    +While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using [Single File Components](https://vuejs.org/v2/guide/single-file-components.html), Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in . These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.`.vue`
    +
    +As a bonus, projects created with the Vue CLI are configured to use files with Webpack out of the box. In fact, if you look inside the folder in the project we created with the CLI, you'll see your first file: .` .vue``src``.vue``App.vue `
    +
    +Let's explore this now.
    +
    +### App.vue
    +
    +Open your file — you’ll see that it has three parts: , , and , which contain the component’s template, scripting, and styling information. All Single File Components share this same basic structure.` App.vue``