Cómo compartir código entre una aplicación web de React y una aplicación móvil de React Native en Monorepo

Rate this content
Bookmark

Por lo general, crear aplicaciones web y móviles requiere diferentes conjuntos de tecnologías, y es bastante difícil compartir código. Esta charla mostrará cómo agregué una aplicación web de React y una aplicación móvil de React Native en el mismo monorepo utilizando Nx, y cómo optimicé el intercambio de código entre la aplicación web de React y la aplicación móvil de React Native.

7 min
20 Jun, 2022

Video Summary and Transcription

Esta presentación se centra en compartir código entre aplicaciones web de React y aplicaciones móviles de React Native. El orador demuestra cómo lograr la paridad de funciones utilizando un Monorepo con NX. Destacan la importancia de compartir código no relacionado con la interfaz de usuario, como la lógica empresarial y la gestión del estado, a través de bibliotecas compartidas. Este enfoque permite que las aplicaciones se centren en el código de la interfaz de usuario mientras mantienen separado el código no relacionado con la interfaz de usuario. Para obtener más detalles, consulte la publicación del blog del orador.

Available in English

1. Introducción a CodeShare y NX

Short description:

Bienvenidos a mi presentación sobre cómo compartir código entre aplicaciones web de React y aplicaciones móviles de React Native. Les guiaré a través de mi experiencia en la construcción de aplicaciones web y móviles utilizando CodeShare. Explicaré los desafíos de utilizar diferentes pilas tecnológicas y cómo logro la paridad de funciones utilizando Monorepo con NX. Comencemos con una demostración rápida creando un espacio de trabajo NX llamado Rack Summit con la aplicación de React llamada Web.

Hola a todos. Bienvenidos a mi presentación. Mi tema es cómo compartir código entre las aplicaciones web de React y las aplicaciones móviles de React Native. Primero, permítanme presentarme. Mi nombre es Emily. Soy una desarrolladora en Toronto y actualmente trabajo para una empresa llamada Narwhal IO. Me gusta hacer senderismo, andar en bicicleta, hacer kayak y todas las actividades al aire libre. Voy a correr una media maratón en octubre de este año, así que me estoy preparando casi todos los fines de semana. Además, solía ser una desarrolladora nativa de iOS, pero eso fue hace mucho tiempo. Afortunadamente, ahora me dedico al desarrollo web. Esta presentación los llevará a través de mi experiencia en la construcción de una aplicación web y móvil utilizando CodeShare. El problema que intento resolver es que tengo esta idea increíble. No solo quiero crear una aplicación web, sino que también quiero crear una versión móvil de la aplicación. Sin embargo, los usuarios esperan experiencias diferentes en la web y en el móvil. Por supuesto, no voy a utilizar el enfoque nativo de iOS y Android porque eso requeriría demasiadas pilas tecnológicas. Naturalmente, elegí Rack y Rack Native como mi pila tecnológica. Sin embargo, todavía hay algunos desafíos. Rack y Rack Native son dos pilas tecnológicas diferentes, el código de la interfaz de usuario es completamente diferente. Rack Native utiliza componentes nativos en lugar de componentes web como base de construcción. Sin embargo, todavía quiero lograr la paridad de funciones, es decir, quiero que la aplicación móvil y la aplicación web tengan las mismas funciones y compartan la misma lógica de negocio. La solución para esto es definitivamente Monorepo. Pero, ¿cuál? La solución que se me ocurrió, no sorprendentemente, es NX. ¿Qué es NX? NX es una poderosa herramienta de Monorepo que configurará las aplicaciones Rack y Rack Native por ustedes, listas para usar. Hagamos una demostración rápida. Primero, creemos un espacio de trabajo NX. En la terminal, ingresen NPX create new workspace. Para este ejemplo, voy a nombrar el espacio de trabajo Rack Summit. Usaré React como el complemento predeterminado y nombraré la aplicación como Web.

2. Compartiendo Código No-UI con Bibliotecas Compartidas

Short description:

Después de instalar los paquetes necesarios y generar la aplicación móvil, exploré el gráfico de dependencias del proyecto. Luego creé una biblioteca compartida llamada 'constants' e la importé tanto en las aplicaciones web como en las móviles. Al compartir código no relacionado con la interfaz de usuario, como la lógica de negocio y la gestión del estado, podemos lograr la paridad de funciones y evitar duplicar código. Esta configuración permite que las aplicaciones se centren en el código de la interfaz de usuario mientras mantienen el código no relacionado con la interfaz de usuario en bibliotecas separadas. Para obtener más detalles, consulta mi publicación en el blog.

Luego de instalar todo, permítanme entrar en esta carpeta de espacio de trabajo e instalar Ahora o el paquete Rack Native. Luego, ingresen el comando para generar una aplicación Rack Native. Nombraré esta aplicación como 'mobile'.

Si abro la carpeta del espacio de trabajo Rack Summit, en las aplicaciones, actualmente hay cuatro carpetas. Tiene la aplicación web y la aplicación móvil que acabo de crear y las carpetas E2E. Si ingreso 'nx serve web', se ejecutará la aplicación web predeterminada de Rack. Mientras tanto, para ejecutar la aplicación móvil, en la terminal, ingreso el comando 'nx run os'. En otra terminal, ingreso 'nx run android'. Esto ejecutará las aplicaciones de iOS y Android en sus respectivos simuladores.

Ahora veamos el gráfico de dependencias. En la terminal, ingresen 'nx graph'. Al ingresar 'nx graph', debería ver el gráfico de dependencias de este proyecto. Observen que no hay nada compartido entre las aplicaciones web y mobile apps.

Luego, creemos una biblioteca compartida. En la terminal, ingresen el comando 'nx generate lib'. Para este ejemplo, la llamaré 'constants'. En la carpeta 'libs', ahora debería ver una carpeta llamada 'constants' que se ha creado. Dentro del archivo 'index.ts', crearé una variable constante llamada 'title'.

Luego, vayamos a la carpeta de la aplicación web. Primero, importaré la variable 'title' desde la biblioteca 'constants'. Después de eso, pasaré la constante 'title' a la propiedad 'title'. Si vuelvo a ejecutar la aplicación web, debería notar que el título ha cambiado. Lo mismo ocurre con la aplicación móvil. También debería poder importar desde la biblioteca compartida y cambiar el título para que provenga de esta biblioteca.

Si abro el gráfico de dependencias nuevamente, debería ver que tanto la aplicación móvil como la web importan desde esta biblioteca 'constants'. Compartir una variable constante no parece ser muy útil. Sin embargo, imaginen qué se podría compartir o qué código no relacionado con la interfaz de usuario se podría compartir. Por ejemplo, la lógica de negocio y la gestión del estado. De esta manera, se garantiza la paridad de funciones para las mismas características, los desarrolladores no necesitan implementar la misma lógica dos veces. Solo necesita existir una vez dentro de una biblioteca compartida.

En esencia, con la ayuda de Next, la configuración del proyecto se vería así. Para las aplicaciones, solo contienen código de la interfaz de usuario. Para el código no relacionado con la interfaz de usuario, podríamos crear bibliotecas para eso. Para obtener más información, pueden consultar mi publicación en el blog enlazada en la parte inferior de la página. Fin. Gracias por escuchar.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

TechLead Conference 2023TechLead Conference 2023
35 min
A Framework for Managing Technical Debt
Top Content
Let’s face it: technical debt is inevitable and rewriting your code every 6 months is not an option. Refactoring is a complex topic that doesn't have a one-size-fits-all solution. Frontend applications are particularly sensitive because of frequent requirements and user flows changes. New abstractions, updated patterns and cleaning up those old functions - it all sounds great on paper, but it often fails in practice: todos accumulate, tickets end up rotting in the backlog and legacy code crops up in every corner of your codebase. So a process of continuous refactoring is the only weapon you have against tech debt.In the past three years, I’ve been exploring different strategies and processes for refactoring code. In this talk I will describe the key components of a framework for tackling refactoring and I will share some of the learnings accumulated along the way. Hopefully, this will help you in your quest of improving the code quality of your codebases.

React Day Berlin 2022React Day Berlin 2022
29 min
Fighting Technical Debt With Continuous Refactoring
Top Content
Let’s face it: technical debt is inevitable and rewriting your code every 6 months is not an option. Refactoring is a complex topic that doesn't have a one-size-fits-all solution. Frontend applications are particularly sensitive because of frequent requirements and user flows changes. New abstractions, updated patterns and cleaning up those old functions - it all sounds great on paper, but it often fails in practice: todos accumulate, tickets end up rotting in the backlog and legacy code crops up in every corner of your codebase. So a process of continuous refactoring is the only weapon you have against tech debt. In the past three years, I’ve been exploring different strategies and processes for refactoring code. In this talk I will describe the key components of a framework for tackling refactoring and I will share some of the learnings accumulated along the way. Hopefully, this will help you in your quest of improving the code quality of your codebases.
React Advanced Conference 2022React Advanced Conference 2022
22 min
Monolith to Micro-Frontends
Top Content
Many companies worldwide are considering adopting Micro-Frontends to improve business agility and scale, however, there are many unknowns when it comes to what the migration path looks like in practice. In this talk, I will discuss the steps required to successfully migrate a monolithic React Application into a more modular decoupled frontend architecture.
React Advanced Conference 2023React Advanced Conference 2023
29 min
Raising the Bar: Our Journey Making React Native a Preferred Choice
At Microsoft, we're committed to providing our teams with the best tools and technologies to build high-quality mobile applications. React Native has long been a preferred choice for its high performance and great user experience, but getting stakeholders on board can be a challenge. In this talk, we will share our journey of making React Native a preferred choice for stakeholders who prioritize ease of integration and developer experience. We'll discuss the specific strategies we used to achieve our goal and the results we achieved.
React Finland 2021React Finland 2021
27 min
Opensource Documentation—Tales from React and React Native
Documentation is often your community's first point of contact with your project and their daily companion at work. So why is documentation the last thing that gets done, and how can we do it better? This talk shares how important documentation is for React and React Native and how you can invest in or contribute to making your favourite project's docs to build a thriving community
React Day Berlin 2023React Day Berlin 2023
29 min
Bringing React Server Components to React Native
Top Content
React Server Components are new topic in community, bunch of frameworks are implementing them, people are discussing around this topic. But what if we could use React Server Components in React Native? And bring all optimisation features that RSC allows to mobile apps? In this talk I would present what we are able to do with RSC in React Native!

Workshops on related topic

React Advanced Conference 2022React Advanced Conference 2022
81 min
Introducing FlashList: Let's build a performant React Native list all together
Top Content
WorkshopFree
In this workshop you’ll learn why we created FlashList at Shopify and how you can use it in your code today. We will show you how to take a list that is not performant in FlatList and make it performant using FlashList with minimum effort. We will use tools like Flipper, our own benchmarking code, and teach you how the FlashList API can cover more complex use cases and still keep a top-notch performance.You will know:- Quick presentation about what FlashList, why we built, etc.- Migrating from FlatList to FlashList- Teaching how to write a performant list- Utilizing the tools provided by FlashList library (mainly the useBenchmark hook)- Using the Flipper plugins (flame graph, our lists profiler, UI & JS FPS profiler, etc.)- Optimizing performance of FlashList by using more advanced props like `getType`- 5-6 sample tasks where we’ll uncover and fix issues together- Q&A with Shopify team
React Summit 2022React Summit 2022
117 min
Detox 101: How to write stable end-to-end tests for your React Native application
Top Content
WorkshopFree
Compared to unit testing, end-to-end testing aims to interact with your application just like a real user. And as we all know it can be pretty challenging. Especially when we talk about Mobile applications.
Tests rely on many conditions and are considered to be slow and flaky. On the other hand - end-to-end tests can give the greatest confidence that your app is working. And if done right - can become an amazing tool for boosting developer velocity.
Detox is a gray-box end-to-end testing framework for mobile apps. Developed by Wix to solve the problem of slowness and flakiness and used by React Native itself as its E2E testing tool.
Join me on this workshop to learn how to make your mobile end-to-end tests with Detox rock.
Prerequisites- iOS/Android: MacOS Catalina or newer- Android only: Linux- Install before the workshop
React Summit Remote Edition 2021React Summit Remote Edition 2021
60 min
How to Build an Interactive “Wheel of Fortune” Animation with React Native
Top Content
Workshop
- Intro - Cleo & our mission- What we want to build, how it fits into our product & purpose, run through designs- Getting started with environment set up & “hello world”- Intro to React Native Animation- Step 1: Spinning the wheel on a button press- Step 2: Dragging the wheel to give it velocity- Step 3: Adding friction to the wheel to slow it down- Step 4 (stretch): Adding haptics for an immersive feel
React Advanced Conference 2023React Advanced Conference 2023
159 min
Effective Detox Testing
Workshop
So you’ve gotten Detox set up to test your React Native application. Good work! But you aren’t done yet: there are still a lot of questions you need to answer. How many tests do you write? When and where do you run them? How do you ensure there is test data available? What do you do about parts of your app that use mobile APIs that are difficult to automate? You could sink a lot of effort into these things—is the payoff worth it?
In this three-hour workshop we’ll address these questions by discussing how to integrate Detox into your development workflow. You’ll walk away with the skills and information you need to make Detox testing a natural and productive part of day-to-day development.
Table of contents:
- Deciding what to test with Detox vs React Native Testing Library vs manual testing- Setting up a fake API layer for testing- Getting Detox running on CI on GitHub Actions for free- Deciding how much of your app to test with Detox: a sliding scale- Fitting Detox into you local development workflow
Prerequisites
- Familiarity with building applications with React Native- Basic experience with Detox- Machine setup: a working React Native CLI development environment including either Xcode or Android Studio
React Summit 2023React Summit 2023
88 min
Deploying React Native Apps in the Cloud
WorkshopFree
Deploying React Native apps manually on a local machine can be complex. The differences between Android and iOS require developers to use specific tools and processes for each platform, including hardware requirements for iOS. Manual deployments also make it difficult to manage signing credentials, environment configurations, track releases, and to collaborate as a team.
Appflow is the cloud mobile DevOps platform built by Ionic. Using a service like Appflow to build React Native apps not only provides access to powerful computing resources, it can simplify the deployment process by providing a centralized environment for managing and distributing your app to multiple platforms. This can save time and resources, enable collaboration, as well as improve the overall reliability and scalability of an app.
In this workshop, you’ll deploy a React Native application for delivery to Android and iOS test devices using Appflow. You’ll also learn the steps for publishing to Google Play and Apple App Stores. No previous experience with deploying native applications is required, and you’ll come away with a deeper understanding of the mobile deployment process and best practices for how to use a cloud mobile DevOps platform to ship quickly at scale.
JSNation 2023JSNation 2023
111 min
Bringing Your Web App to Native With Capacitor
WorkshopFree
So, you have a killer web app you've built and want to take it from your web browser to the App Store. Sure, there are a lot of options here, but most will require you to maintain separate apps for each platform. You want your codebase to be as close as possible across Web, Android, and iOS. Thankfully, with Capacitor, you can take your existing web app and quickly create native iOS and Android apps for distribution on your favorite App Store!
Contents: This workshop is aimed at beginner developers that have an existing web application, or are interested in mobile development. We will go over:- What is Capacitor- How does it compare to other cross-platform solutions- Using Capacitor to build a native application using your existing web code- Tidying up our application for distribution on mobile app stores with naming conventions, icons, splash screens and more