Tutorial: How to share code between iOS, Android & Web using React Native, react-native-web and monorepo

Bruno Lemos on March 06, 2019

Let's make our react-native app work in the browser, the right way. This tutorial was last tested on react-native@0.61.x. If you are using a diff... [Read Full]
markdown guide
 

HELP! something changed and i cannot replicate this tutorial anymore. i cannot get past the first time you are testing android studio. I remember something like --version react-native@next that is now missing from this tutorial. and now i cannot replicate it at all some one please help.

this is now the 7th time im following the instructions and i get this error first time i try test in the android simulator after trying to create monorepo

Unable to resolve module `./packages/mobile/index

 

Hi, I updated the tutorial with the latest changes from react-native@0.59, search for projectRoot to see the updated step involving the file metro.config.js.

 

thank you so much for the new changes in the tutorial. i made the changes to the metro.config.js just like you suggested and i can now run it on android. i will continue with the rest of the tutorial in the morning.

 

Hey Bruno how are you?

Im still running into a issue. Soon as i complete the web section of the tutorial. my mono repo breaks for mobile. it installs all the modules in packages/mobile/node-modules instead of root/node_modules.

Thus when I run packages/mobile/yarn start i get the following error
"Error: Cannot find module 'E:\2019_PROJECTS\moco-messenger-project\code\repo\test\node_modules\react-native\local-cli\cli.js'"

I dont understand how the web project is affecting the mobile project. Please assist.

kind regards

Make sure you have the correct content inside the root package.json and you used yarn at the root directory to install the dependencies, not inside each package neither npm instead of yarn.

Compare your code with the repository to see if anything is different: github.com/brunolemos/react-native...

hey bruno,

I just did like you said, I even upgraded react-native to v0.59.0 stable. yet still when i run yarn in the root it still installs packages/mobile/node-modules and not in root/node_modules.

how can i compare an entire project with difference in vs code? are you sure there isnt a step missing? I have tried 3 times now following your exact instructions.

Do you have the latest version of nodejs and yarn? How is your root package.json?

I just checked on my computer, im running yarn 1.130 and node v10.0.0 i believe those are the latest versions.

my root package.json file looks exactly like yours.

{
"name": "myprojectname",
"version": "0.0.1",
"private": true,
"workspaces": {
"packages": [
"packages/*"
]
}
}

like i said im extremely confused becasue i dont understand why the monorepo breaks when i add the web

i just downloaded your project at
github.com/brunolemos/react-native... and when i run yarn in the root it is also installing the packages in the wrong places.

Hey everyone, I downloaded the project, followed the updated tutorial and ran into the same exact issue. I got /mobile running again by updating the relative filepath in its package.json to the react-native-cli:

"scripts": {
    "start": "node ./node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },

good luck!

Hey, you both were right! React Native started getting installed inside packages/mobile/node_modules, which is wrong. Changing the path is not the right solution though.

I investigated and you need to make sure all your dependencies have the exact same version between the monorepo packages. For example, change your "react" dependency inside the mobile and web's package.json to the exact same version (e.g. 16.8.4).

This will make react-native get installed in the root node_modules again and also prevent multiple instances of react being installed in the same project, which would cause all kinds of bugs.

Updated the tutorial and also the repository: github.com/brunolemos/react-native...

 

Hi Bruno,

How to use 3rd lib, I want to add react-native-element package.
It's work well on mobile, but when I run web app, it's error below:

Support for the experimental syntax 'classProperties' isn't currently enabled (41:23):

  39 | 
  40 | export default class SwipeRating extends Component {
> 41 |   static defaultProps = {
     |                       ^
  42 |     type: 'star',
  43 |     ratingImage: require('./images/star.png'),
  44 |     ratingColor: '#f1c40f',

Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.

Here's what I added to config-override.js on packages/web

const appIncludes = [
  ...
  resolveApp('../../node_modules/react-native-elements'),
  resolveApp('../../node_modules/react-native-vector-icons'),
]

module.exports = function override(config, env) { 
  ...
  config.module.rules[2].oneOf[1].options.plugins = [
    require.resolve('babel-plugin-react-native-web'),
    require.resolve('@babel/plugin-proposal-class-properties'),
  ].concat(config.module.rules[2].oneOf[1].options.plugins)
  ...
}

In future, I will add react-navigation and some other packages.
Please help, many thanks!

 

Did you make it work?

I haven't tried your code but yes, changing config-override.js correctly should be enough.

 

Was anyone able to add react-navigation to the project? I got react-native-elements working by following the above comment.

Here's a working example for React-Navigation with web :
github.com/react-native-elements/r...

Thank for documenting all this work thoroughly.
As a React-Native noob, this guide was very easy to follow along ! Cheers!

I got react-navigation's drawer working on the web.

The following is my config-override.js

const fs = require('fs')
const path = require('path')
const webpack = require('webpack')

const appDirectory = fs.realpathSync(process.cwd())
const resolveApp = relativePath => path.resolve(appDirectory, relativePath)

// our packages that will now be included in the CRA build step
const appIncludes = [
  resolveApp('src'),
  resolveApp('../components/src'),
  resolveApp('../../node_modules/@react-navigation'),
  resolveApp('../../node_modules/react-navigation'),
  resolveApp('../../node_modules/react-native-uncompiled'),
  resolveApp('../../node_modules/react-native-elements'),
  resolveApp('../../node_modules/react-native-gesture-handler'),
  resolveApp('../../node_modules/react-native-ratings'),
  resolveApp('../../node_modules/react-native-screens'),
  resolveApp('../../node_modules/react-native-tab-view'),
  resolveApp('../../node_modules/react-native-vector-icons'),
  resolveApp('../components/libraries/MSALAuthLogin'),
  resolveApp('../../node_modules/react-native-vector-icons'),

]

module.exports = function override(config, env) {
  // allow importing from outside of src folder
  config.resolve.plugins = config.resolve.plugins.filter(
    plugin => plugin.constructor.name !== 'ModuleScopePlugin'
  )
  config.module.rules[0].include = appIncludes
  config.module.rules[1] = null
  config.module.rules[2].oneOf[1].include = appIncludes
  config.module.rules[2].oneOf[1].options.plugins = [
    require.resolve('babel-plugin-react-native-web'),
    require.resolve('@babel/plugin-proposal-class-properties'),
  ].concat(config.module.rules[2].oneOf[1].options.plugins)
  config.module.rules = config.module.rules.filter(Boolean)
  config.plugins.push(
    new webpack.DefinePlugin({ __DEV__: env !== 'production' })
  )

  return config
}

thanks for the input
i am facing similar issue while using GoogleSigninButton from react-native-google-signin.

i tried adding require.resolve('@babel/plugin-proposal-class-properties') as you suggested below.

also tried to update babel.config.js with the following, didnt worked as well...
module.exports = {
plugins: [
[
'@babel/plugin-proposal-decorators',
{
legacy: true,
},
],
[
'@babel/plugin-proposal-class-properties',
{
loose: true,
},
],
'@babel/plugin-syntax-dynamic-import',
'@babel/plugin-transform-regenerator',
[
'@babel/plugin-transform-runtime',
{
helpers: false,
regenerator: true,
},
],
],
presets: ['@babel/preset-flow', 'module:metro-react-native-babel-preset'],
}

also tried with loose: true
require.resolve('@babel/plugin-proposal-class-properties', {
loose: true,
}),

any suggestion please?

thanks for you time.

Hi Oz, were you able to make it run? Did you try with a compatible release (any before 0.60)?

Hi Nishant,

Unfortunately I was not able to solve it.
I am not sure about earlier versions but I went over many possible suggestions, none of them worked...
Any additional idea that I can try?

Thanks for the reply

Use this config to fix the issue

config.module.rules.push(
    {
        test: /\.js$/,
        use: {
            loader: 'babel-loader',
            options: {
                // Disable reading babel configuration
                babelrc: false,
                configFile: false,

                // The configration for compilation
                presets: [
                    '@babel/preset-env',
                    '@babel/preset-react',
                    '@babel/preset-flow'
                ],
                plugins: [
                    '@babel/plugin-proposal-class-properties',
                    '@babel/plugin-proposal-object-rest-spread'                  
               ]
            }
        }
    }
)

Add the above code before the return config line

Thanks Rajendran

i tried adding the above as part of config-overrides.js
it didn't helped.

BTW, i`ve executed 'sudo yarn add @react-native-community/google-signin'

Under the folder 'react-native-web-monorepo/packages/components'
Is that the right location?

Thanks, Oz

An update...
i had to add two more dev dependencies under the web module.
sudo yarn add --dev babel-loader
sudo yarn add --dev @babel/preset-flow

now i am getting different error:
/react-native-web-monorepo/node_modules/@react-native-community/google-signin/src/GoogleSigninButton.js
Attempted import error: 'requireNativeComponent' is not exported from 'react-native'.

 

Really great stuff, we learn a lot!

Here is what we wrote on somewhat the same topic.

reily.app/posts/2019-02-25/firebas...

It was too much trouble to set up both Android, iOS and their native dependencies in the mono repo structure.

So we decided to just nohoist everything. T_T

 

Nice, thanks for the mention in the article!

Were you able to share code between web and mobile using nohoist? I've had problems with this approach in the past but I don't remember exactly why. It has some downsides but it's definitely much simpler to setup. Everything working well for you this way?

 

No, sry for taking so long to reply.

Our yarn workspace is just set up to include app / backend / website

And they do not share components.

The problem is that metro does not support symbol links. Which is what yarn workspace uses.

github.com/facebook/metro/issues/1

 
scripts: {
  "start": "node ../../node_modules/react-native/local-cli/cli.js start --projectRoot ../../"
}

throws error error: unknown option `--projectRoot'

On modifying --projectRoot to --projectRoots I get following error

Loading dependency graph...jest-haste-map: Watchman crawl failed. Retrying once with node crawler.

 

You mean when trying to use jest? If not please check the repository to see what you made differently.

 

Sorry, I modified my comment. I am getting an error with --projectRoot. I was trying on my own repo. I'll be cloning your repo and then let you know if the problem persists.

I'm using the unreleased react-native 0.59 in this tutorial, some dependencies got a major bump so maybe there are some differences if you are using an older version.

 

did you find an alternative for --projectRoot please ?

 

Hi Bruno, thanks for the awesome detailed tutorial with all the updates. And i can see you are very active in comments also which is awesome!

Its really nice to see react's progress towards PWA and cross platform portability.

I am following this tutorial to convert our old add(on Rn 0.59) over to react-native web. I followed this tutorial and setup everything up.
Than i copied the dependencies from our mobile repo's package json to packages/components/package.json. And all other code respectively in src. Idea was to get everything running on ios in this monorepo setup and than go from there to fix whatever needs to be fixed for web.

But i am getting some errors like first i got:

bundling failed: Error: Unable to resolve module path from /Users/..../projec/node_modules/react-native-dotenv/index.js: Module path does not exist in the Haste module map

Fixed it by adding path explicitly in dev-dependencies. Than started getting error:

bundling failed: Error: While trying to resolve module fs from file /Users/..../projec/node_modules/babel-plugin-dotenv/index.js, the package /Users/..../projec/node_modules/fs/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/..../projec/node_modules/fs/index.js. Indeed, none of these files exist

I am not very experienced in react and react-native, i am mainly on Ruby on Rails, so maybe this is something basic which i am getting wrong.
I found: stackoverflow.com/a/39046690/4738391 which suggests omething wrong with node environment or something. But i am a bit confused, i mean i can add these dependencies etc but it should work out of the box for mobile, as it was working fine in previous repo.

Any help will be greatly appreciated. Thanks.

 

This was a stupid error, i had forgot to add 'module:react-native-dotenv' in my babel config presets. Adding it solved the problem and i got my mobile app compiled. There were some imports fixes etc in scode needed to be done to run app successfully. But that is done.

But now next errors(on web), i posted this SO question: stackoverflow.com/questions/571953...

If i can get any help, would be great.

 

Please remove all node_modules folders and .lock files from your project, clear all caches (xcode, —reset-cache, etc), and try following the steps again. Maybe you missed something.

You shouldn’t remove the dependencies from mobile. Check this repo source code and commit diffs: github.com/brunolemos/react-native...

After running yarn to install dependencies, check the contents of packages/mobile/node_modules, and let me know which folders it has. It shouldn’t have any, all should be in the root node_modules.

If nothing works, maybe they released a new version of the cli that broke something, in that case you can use a previous version or investigate the change.

 

I think i was not clear in my comment, actually it did work with barebone setup as described in this post. It was working perfectly, than i started exporting my mobile code, that's when it exploded.

I wanted to just have mobile app running as it is in this architecture. Than move un-convertable code to mobile and write replacement code for only those in web. But my mobile app is not running with these errors.

I did all the cache clear and everything but same issue. mobile repo's node_modules folder have 2 folder, .bin and metro-react-native-babel-preset.

I am pretty sure it is some of my mobile dependency. I don't know if i should share the package json etc and everything here. It will just get annoyingly long here.

Let me know if i should share that here, or i can reach you through some other medium.

I do understand this blog post is like THE go to blog right now for new projects which want to take this route. but porting old projects is a lot more messy. If i do succeed in porting my app on this architecture and support web, i will leave pointers and can also write an extension of this blog post.

 

After cache clean and everything, second error changed to:
error: bundling failed: Error: While trying to resolve module fs from file /Users/..../projec/node_modules/babel-plugin-dotenv/index.js, the package /Users/..../projec/node_modules/fs/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/..../projec/node_modules/fs/index.js. Indeed, none of these files exist

 

Having some troubles getting react-native-web hoisted and getting everything to run. It insists on staying inside the web/node_modules together with fbjs and react. I do have some nohoist packages that are linked in the mobile project. I verified all the version numbers. They seem to be aligned

Tried various cleaning actions. I'm getting errors from hoisted elements not being able to find react-native-web shouldn't metro-react-native-babel-preset be implemented as a preset in the web project? This seems to be indicated in react-native-web examples

 

You need to use the exact same version of react between all package.json that have it.

 

You can run debug session from vscode with React Native Tools extension. But with monorepo its little hacky... btw, read-native run-its --project-path "./packages/mobile/ios" also work

I setup only iOS project with macos: you need to specify "runArguments": ["--project-path", "./packages/mobile/ios"] in debug task in launch.json and symlink with command:

ln -s /Users/proof666/Desktop/Projects/ShopList_new/PaperList/packages/mobile/ios  /Users/proof666/Desktop/Projects/ShopList_new/PaperList/ios

~if somebody already setup android debug, please ping me~
Update:
in vscode task for android add

...
"runArguments": ["--root", "./packages/mobile"] 
 
 

Number of issues here:
Changing jsBundleURLForBundleRoot:@"index" to jsBundleURLForBundleRoot:@"packages/mobile/index" leads to resolution errors
Leaving it as it is, leads to @babel/runtime/helpers/interopRequireDefault does not exist in the Haste module map. It looks like the packages/mobile/index reference is the way to go but that the react-native command uses packages/mobile as the ref location instead of the project root. From the root I tried two commands (RN 0.59):

mobile: start => ../../node_modules/.bin/react-native start --reset-cache
root: start => cd ./packages/mobile && yarn start
root: start => yarn workspace mobile start

In both cases, I get "Unable to resolve module ./packages/mobile/index from /Users/me/projects/rnw/packages/mobile/.
[...]
`Indeed, none of these files exist:

  • /Users/me/projects/rnw/packages/mobile/packages/mobile/index

Notice the duplicate packages/mobile reference

 

Ok, I identified the problem. The packages/mobile/metro.config.js is not processed. The projectRoot remains packages/mobile instead of ``

 

Hi,

I'm facing the same problem. Did you manage to solve why the metro.config.js wasn't processed?

Current solution is to set --projectRoot ../../ at the package.json start script instead of metro.config.js, like it used to be before. Not sure if it's a bug or not.

 

Hello Bruno,

1.) Now that Expo for Web was released, what would you recommend?
To setup a monorepo for Mobile and Web packages or to use Expo for Web?
There's also a React Native Web CLI called create-react-native-web-app.

2.) And also could you give some guide how to setup Next.js as a package of this monorepo? Upon running yarn create next-app --example with-react-native-web next, here's the response:

PS C:\Users\USERNAME\Documents\Node.js Projects\Samples\myprojectname\packages> yarn create next-app --example with-react-native-web next
yarn create v1.16.0
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Installed "create-next-app@0.5.9" with binaries:
      - create-next-app
- Downloading files for with-react-native-web example[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4
DEPRECATED (@octokit/rest): `repos.getContent()` is deprecated, use `repos.getContents()`
> Success! Downloaded with-react-native-web files for next

  Installing npm modules:
    react
    react-dom
    next

> Error! Failed to install react, react-dom, next, try again.
undefined
(node:12428) UnhandledPromiseRejectionWarning: Error: yarn installation failed
    at C:\Users\USERNAME\AppData\Local\Yarn\Data\global\node_modules\create-next-app\lib\utils\install.js:39:23
    at processTicksAndRejections (internal/process/task_queues.js:82:5)
(node:12428) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:12428) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Node.js process with a non-zero exit code.
Done in 17.47s.

Thanks for any response!

 

Expo has it's own set of limitations, e.g. I've been using hooks in production since november 2018 and it only arrived in expo may 2019. If you are ok using expo go for it! They seem to be doing great progress.

About next, I don't know what the issue is, try creating the project separately and copy pasting the folder into the monorepo. Otherwise open an issue with them about monorepo support.

 

Thanks a lot for this great tutorial.

i`ve probably missing it in the comments but i am not sure what pakage.json i should use for adding additional dependencies.
should i only update the root /package.json
or individually also

  • packages/components/package.json
  • packages/mobile/package.json
  • packages/web/package.json

in addition, only yarn should be used?

Thanks again.

 

Yes only yarn because npm doesn’t have the “workspaces” feature.

You’ll add the dependencies in the package that’s using them. Most of it will probably be in the components. Don’t add at the root unless it’s things like lint etc.

 

Hello,

Thank you so much for the article.

I have pulled down your repo, installed the deps and ran it. Metro bundler runs well but I do not see anything on the emulators.

Is there a step that I am missing?

Thanks

Siya

 

To run the mobile apps you can open Xcode/Android Studio and press the Run button.

 

Yeah, I realised that is how you were running it. I am a fan of the terminal, so I prefer that way. But for some reason I thought that running the bundler would mount the project into the emulator. Thank you so much for the article, I found it very helpful.

How did you configure auto reloading?

Thanks

 

Sir, will createBrowserApp(switchNavigator, { history: 'browser' }) work when I host a React Native Web app on GitHub Pages to have such these URLs:

  • username.github.io/Home
  • username.github.io/Links
  • username.github.io/Settings

Is it possible on GitHub Pages with React Native Web?

 

I want to discuss something we are facing after getting a great kickstart from this post. That is responsiveness problem.

We have made significant progress in our journey of converting existing RN apps to RNW. In-fact i am now writing a series of articles on my experience, first one was written last weekend and i plan on writing next this weekend. Here is the first part:
medium.com/@ziaulrehman/part-1-con...

For my use case, i am using a similar approach to this library: github.com/calinortan/react-getscreen it basically adds event handlers which trigger a state change hence re-render whenever screen size crosses one of pre-defined(configurable) widths.
This allows us to add conditional styles etc on some elements, or even hide/show some elements conditionally. This along with Platform.OS === 'web' is basically all we are doing for now. It doesn't look very clean but it works and gives us responsive design.

What techniques have you used(if any) for this? What worked best? And what would you suggest. Thanks.

 

I have a custom hook that checks the app dimensions and returns if it’s small/medium/large: github.com/devhubapp/devhub/blob/m...

Besides that, make sure to always use flexbox and percentages where makes sense, not fixed widths in pixels.

 

Yeah similar approach with HOC for class components. I actually just released a small RN component for this(actually my first npm package). npmjs.com/package/react-native-get...

 

Hello Bruno, awesome tutorial as I mentioned!

I have another question though, and it's related to builds. I've set the build phase as Release (so I can run it without a server) but I get an error in Xcode:

File /Users/--/Library/Developer/Xcode/DerivedData/project-name/Build/Products/Release-iphoneos/project-name.app/main.jsbundle does not exist. This must be a bug with'

Is there anything special I need to set here to get Xcode to build it?

 

No, this error is unrelated to this tutorial. Try cleaning the caches, e.g. Product > Clean and yarn start --reset-cache.

 

Thank you cheers! I had thought it was something related to the workspace edits. Turns out there's an issue in react-native about github.com/facebook/react-native/i....

So how did you fix it? I have the same issue. The GitHub issue link you provided is not working for me :-/

 

With the react-native-version 0.60.4, I have some problems with libhermes.
When starting the android-app, it crashes and I always get the message: E/SoLoader: couldn't find DSO to load: libhermes.so. Any suggestions what to do?

Edit: Fixed my problem. You have to enable hermes, so that it looks like this in your build.gradle in app:
project.ext.react = [
entryFile: "packages/mobile/index.js",
root: "../../../../",
enableHermes: true, // clean and rebuild if changing
]

 

Olá bruno, baixei a versão mais recente do monorepo, mas está dando esse erro,
sabe dizer porque? e como resolver?

Loading dependency graph, done.
[1] error: bundling failed: Error: Unable to resolve module ../../../commons/reducers/ from E:\sistemasagv\appwmsmobile\app-rf\packages\components\src\screen-mobile\Reducer\index.js: The module ../../../commons/reducers/ could not be found from E:\sistemasagv\a
ppwmsmobile\app-rf\packages\components\src\screen-mobile\Reducer\index.js
. Indeed, none of these files exist:
[1] * E:\sistemasagv\appwmsmobile\app-rf\packages\components\commons\reducers(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
[1] * E:\sistemasagv\appwmsmobile\app-rf\packages\components\commons\reducers\index(.native||.android.js|.native.js|.js|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
[1] at ModuleResolver.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:163:15)
[1] at ResolutionRequest.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:52:18)
[1] at DependencyGraph.resolveDependency (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\node-haste\DependencyGraph.js:283:16)
[1] at Object.resolve (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\lib\transformHelpers.js:261:42)
[1] at dependencies.map.result (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:399:31)
[1] at Array.map ()
[1] at resolveDependencies (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:396:18)
[1] at E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:269:33
[1] at Generator.next ()
at asyncGeneratorStep (E:\sistemasagv\appwmsmobile\app-rf\node_modules\metro\src\DeltaBundler\traverseDependencies.js:87:24)


 

Bruno, this is a great tutorial. I have been able to successfully migrate an existing react native project to the mono repository and can run and compile the mobile app for android. However, I am having issues building the web portion of the project. Any tips on how to debug? I am getting the project to start to compile but get in error Attempted import error: 'initStore' is not exported from '../store'. I have altered the index.js for web to pull in the components package.

Thanks

 

Is it possible to incrementally add rnw to an existing project?
The current project set up is a 3 package monorepo with redux being the only code that is shared. The goal is to share more code so I’m thinking to create a 4th package that only contains react native web components and is imported by the react and react native packages. Do you see any issues with this approach or pieces not working?

 

HELP!!!!!!

I have implemented react-navigation-drawer in my project. Just using two menu items there
( HomeScreen & ProfileScreen )

  1. When the screen loaded first time ProfileScreen works perfectly but Second time it shows blank white screen on the browser. If I refresh screen then repeat the previous flow. First time works second time blank white screen.

react-navigation-drawer issue link

  1. The drawer not closing automatically on the browser ... but on mobile it works fine.

  2. Can you please give me any reference where i can separate the style of web and mobile?

 

I made an account just to thank you for this. I've been struggling getting RNW to work, and when I got it working it was only for old versions of react with some hacky fixes.

PS: I tried following this tutorial but for some reason couldn't build with XCode, so I just cloned your repo and it worked out of the box!

 
 

Hi, thanks for this tutorial, monorepo is amazing, however how could rename project "myprojectname" to "mycustomname" properly?

Other hand side, for windows to start android studio, add enviroment var to PATH var list:
...
C:\Program Files\Android\Android Studio\bin
...
and replace:

"studio": "START /B studio64 android",

Thanks

 

Hey Bruno, don't know if you can't help me but I've followed the post to setup the monorepo. Almost everything worked, web is working well, but I'm having trouble with the React Native part.

I think the problem is that some dependencies are being installed on the workspace node_modules instead of the project's root node_modules so some dependencias are in the root and others are inside the project - almost as if it was set to no-hoist these dependencies (it was not).

Do you any clue why this is happening?

Thanks for writing the post

 

when you say, "You can now run the Android app! 💙" what does that mean? what steps do i take to run the app?

 

There is a "Run" green button inside Android Studio that will open the app inside an emulator.

 

Thank you so much. I just wanted to make sure that im not missing anything because I couldn't get "react-native run-android" to work.

You have several options to make react-native commands work.

  • in the node_modules directory of your package make a symlink to the node_modules/react-native directory from the root of the project because react-native-cli need to find cli.js in node_modules/react-native.
  • prefix your command with yarn or npm : yarn react-native run-android
  • in your package.json file add a script "run-android": "react-native run-android" and then use yarn run-android

I used second option. However, I am using third party libraries and it cannot resolve these dependencies!

Could not resolve project :react-native-navigation.
Required by:
project :app
> Unable to find a matching configuration of project :react-native-navigation: None of the consumable configurations have attributes.
Could not resolve project :react-native-vector-icons.
Required by:
project :app
> Unable to find a matching configuration of project :react-native-vector-icons: None of the consumable configurations have attributes.

Solved,
I changed projectDir attribute of library in android/settings.gradle

 

Hey, I'm looking at your articles(very comprehensive), among others, and trying to understand the need to add CRA to the stack, here. Would using react-native and react-native-web not do the trick?

Also, changing the import statements in node_modules means you check in your node_modules? Or you make the edits every time you yarn install? (or, i missed smth with yarn workspaces 🤔?)

Thanks for your time and for the article!

 

CRA makes things easier, but it is not required.

It doesn't make any change inside node_modules, only on normal project files.

 

Is the --projectRoot flag a metro config option? trying to set this up with the 0.59.0 release and running into haste map resolution issues for @babel/runtime

 

Please refresh the page, I've updated the tutorial a few minutes ago with the new step related to projectRoot. You don't set --projectRoot anymore, you add it to metro.config.js.

 

ha - thank you. i had just made and tested the same update and got it working. cheers!

 

Thanks, Bruno! I really needed this. Can this be applied to Lerna instead of Yarn Workspaces?

 

I've never used Lerna because Yarn Workspaces does all I need, so I don't know the answer. But let us know! 🙌

 

Nice article, I have a bit similar example for code sharing between react-native and next.js with react-native-web here: infinidraw.live/

Source: github.com/msand/InfiniDraw
Expo version: github.com/msand/InfiniDrawExpo

But, it's not really clean architecturally, it's a single project rather than separate folders & package.json for web and native, causing some tradeoffs. Been thinking should slit it up a bit similar to this.

 

Hi, after going through the steps listed under "ios changes" above, when i run "yarn workspace mobile start" it does launch the app in the simulator but i get a red screen with error (attaching image). Please help

 

Hi, I have a question that I cannot grasp , where is the rule that allows to have different environments files? .web , .android , .ios, .native , etc and being selected auto-magically ?

 

This is handled by react-native and create-react-app.

 
 

Nice article, thanks!

Any more info on „If you use expo, there may be some news coming to you soon“? 😇

 

I believe they are about to release built-in web support soon, but I have no insider information, it's just an impression I had after seeing some tweets from their team members. Also some of their dependencies recently got web support merged. You can ask them for more details: twitter.com/Baconbrix/status/10983...

 
 

It says "(electron for now)", what are the plans for this? I love the idea for a setup like this, but would also love to hear where you have spotted potential improvement in this regard.

 

It's possible to have native apps instead of Electron, with the same code. We can use react-native-windows and react-native-macos, for example. In a few days I'll experiment with Marzipan, a secret official Apple project to run iOS apps on the mac.

 

Ah! Fantastic. I plan on actually implementing this approach on a brand new project so this article came at the perfect time. Appreciate the response too because of course I'd prefer to skip the electron step if the other options prove to be better -- and leveraging the freedom of a brand new project while it lasts.

 

Is it any chance this will work with RN 0.6? There is a problem with --projectRoot param, as 0.6 doesn't recognize this parameter. Checked your GH repository, looks like you are still working with 0.59

 
 

Hi Bruno, In the DevHub app for the web or windows, how did you get multiple screens to fit in parallel (Side by Side) ? Can you point me in the correct direction.

I tried reading the code but could not understand it as I have no idea how electron works with React-Native. Anything would help.

Also, a bigg thank you for updating this tutorial.

 

If you are talking about the columns, they aren't "multiple screens" in parallel, it's just an horizontal FlatList component. About modals and other navigation components, I wrote from scratch, since I'm not using any navigation library (I may use some soon).

 

Hi, first of all: thank you, thank you so much for the guide, it was the only way, for me, to correctly setup my project.
Then, i've two suggestions:

1) The guide talks about sharing the "components", so i was fearing i had to reqrite all the routing, sagas, redux, etc, etc part for web. Instead i found the project share the whole app, so maybe "components" is not the perfect word here?

2) I had to add some components that, to work on web, required to use another custom web component and add the alias to webpack (es: react-native-linear-gradient/react-native-web-linear-gradient).
I used customize-cra (github.com/arackaf/customize-cra) but it took me some time to port the actual webpack's override i had (from this guide) to the customize-cra one with the alias. Don't you think it would be nice to use customize-cra on this guide? Or maybe just explain a way to create the alias without the customize-cra module?

Thank you for the great job.

 

Amazing work, congratulations!
Did you consider using react-navigation for web and native or react-router just for web?
What made you skip those options?

Thank you

 

React Navigation v3 wasn't available yet, v2 didn't work very well on web. I may use it on next projects if it is better now.

 
 
[deleted]
 

HELP! this is the 6th time i have tried to replicate this tutorial, but something changed and i cannot replicate this tutorial anymore. i cannot get past the first time you are testing android studio. I remember something like --version react-native@next that is now missing from this tutorial. and now i cannot replicate it at all some one please help.

the error reads "Unable to resolve module ./packages/mobile/index"

 

how many changes occurrences of node_modules/react-native/ are you replacing with ../../node_modules/react-native/ vscode picks up 26 places where i change it. is this correct?

i cannot get it to work please assist.
Error: Unable to resolve module ./packages/mobile/index from E:\2019_PROJECTS\moco-messenger-project\code\repo\wepay4\packages\mobile/.: The module ./packages/mobile/index could not be found from E:\2019_PROJECTS\moco-messenger-project\code\repo\wepay4\packages\mobile/..

 

I've believe that the monorepo was installed correctly react-native was installed in the root directory. What confused me was this step "Open your favorite editor and use the Search & Replace feature to replace all occurrences of node_modules/react-native/ with ../../node_modules/react-native/". I'm over here like what occurrences? Where exactly are the occurrences? In what files? Any help, please and thank you.

 

My package manager responds to http://localhost:8081/packages/mobile/index.js but gives a 404 on http://localhost:8081/packages/mobile/index. Any ideas?

 

I also see this error Error: Unable to resolve module ./packages/mobile/index from /Users/boo/project/packages/mobile/.: The module ./packages/mobile/index could not be found from /Users/boo/project/packages/mobile/.

Indeed, none of these files exist:
  * /Users/boo/project/packages/mobile/packages/mobile/index(.native||.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)

There seems to be a path set wrong. But it all looks ok at the code level

 
 

No, Workspaces is a feature available on Yarn but not on the npm cli, afaik.

 
 

Next.js has an official example using react-native-web, check it out: github.com/zeit/next.js/tree/maste...

 
 
 

I have a problem with build android: Text must not be null or empty in react native 0.60 build error

 

Thanks Bruno , Can we use react-native run-ios or android at packages/mobile folder ? I want to start the simulator .

 
 

Great article, thanks! Really helped me to transform existing project to monorepo. Except one babel plugin. Any thoughts on how to get babel-plugin-module-resolver working with your structure?

 

I wonder how you rate the viability of using RNW in production with RN0.59, given that the current supported version is 0.55 with 0.57 under construction

 

I've been using it on DevHub with no problem. What it means is that the javascript code running on the web is the one from rn-0.55, not rn-0.57. This will start to become an issue when react-native remove some components, for example, so react-native-web will need to stay up to date.

 

react-native gets installed on packages/mobile/node_modules, even though monorepo dependencies share the same version.

 

I could not reproduce. Check the versions of all packages again, remove the "" from the start of them. You can fork this instead: github.com/brunolemos/react-native...

code of conduct - report abuse