To use shared assets between React and React Native in an Nx Workspace, you can follow these steps:

  1. Create a Shared Library: In your Nx Workspace, create a new library that will contain the shared assets (e.g., images, styles, fonts, etc.). This library will be used by both the React and React Native applications.
bash
# Replace 'shared-assets' with the desired name for your library nx generate @nrwl/workspace:library shared-assets
  1. Add Assets to the Shared Library: Place all the shared assets (e.g., images, styles, fonts) in the appropriate directories within the newly created shared library.
plaintext
apps/ libs/ shared-assets/ assets/ images/ styles/ fonts/
  1. Configure Asset Paths: Update the angular.json file (for the React application) and the react-native.config.js file (for the React Native application) to include the asset paths from the shared library.

In angular.json:

json
{ "projects": { "your-react-app": { "architect": { "build": { "options": { "assets": [ "apps/your-react-app/src/assets", { "glob": "**/*", "input": "libs/shared-assets/assets", "output": "shared-assets/assets" } ] } } } } } }

In react-native.config.js:

javascript
module.exports = { assets: ["./assets", "libs/shared-assets/assets"], };
  1. Import and Use Shared Assets: Now you can import and use the shared assets in both your React and React Native applications. For example, in your components or styles:

In React:

jsx
import React from 'react'; import logo from 'shared-assets/assets/images/logo.png'; const MyComponent = () => { return <img src={logo} alt="Logo" />; };

In React Native:

jsx
import React from 'react'; import { Image } from 'react-native'; import logo from 'shared-assets/assets/images/logo.png'; const MyComponent = () => { return <Image source={logo} />; };

By following these steps, you can centralize your shared assets in a single library within your Nx Workspace, making it easy to use the same assets across both your React and React Native applications. This approach helps promote code reusability and consistency in your multi-platform project.

Have questions or queries?
Get in Touch