9

I'm trying to build a project out for all platforms that share code between web, desktop and native applications. Does anyone have experience setting up cross platform code-sharing using react, react-native, electron and webpack and knows some resources/examples to get me started on achieving this?

The directory structure might look something like this:

/resources (fonts, images)
/config (webpack config)
/fastlane (android + ios build/deployment)
/android (auto generated by expo or create-react-native-app maybe?)
/ios (auto generated by expo or create-react-native-app maybe?)
/web
/desktop
/src (components, styles, pages, routes, App.js, etc... all shared)
index.js

I plan to run and build each platform with scripts such as this:

/package.json

"scripts": {
  "ios": "react-native run-ios",
  "android": "react-native run-android",
  "desktop": "electron .",
  "web": "webpack-dev-server --open",
  "build: "webpack",
  "desktop-build": "electron-builder --config config/electron.config.js",
  "ios-build": "fastlane ios build",
  "android-build": "fastlane android build"
}

Setting up this webpack config seems the most difficult part. I'm not even sure how I would go about initializing this project yet. I use custom webpack setups for web, but never have with react-native. Could i initialize this project with create-react-native-app or expo and then eject and write in the expo/web configs after?

As far as the react code goes I think it will be pretty straightforward though.

It can utilize react-native for all JSX on each platform's using react-native and react-native-web.

/index.js

AppRegistry.registerComponent('App', () => App);

Each file in the components can have platform specific code via naming:

index.js
index.native.js (ios + android)
index.ios.js
index.android.js
index.desktop.js

That should enable routing like such:

/index.js
import {
  BrowserRouter as Router,
  Switch,
  Route
} from 'react-router-dom';

/index.native.js
import {
  NativeRouter as Router,
  Switch,
  Route
} from 'react-router-native';

/App.js
import {
  Router,
  Switch,
  Route
} from './router';

export default App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={WhateverPage} />
      </Switch>
    </Router>
  )
}

Would love to hear some thoughts and experiences from other developers on this!

Ryne
  • 1,195
  • 2
  • 14
  • 32
  • What did you end up doing? – Mahmoud Mousa Hamad Jun 25 '22 at 03:15
  • I previously setup a project using yarn workspaces like this, It has a frontend react app, ssr app and a react native app each having an independent workspace and package.json but yarn managers the package sharing and hoisting. One of the workspaces was called "shared" a directory in which we keep the react components or screens that are to be shared between that apps. – Aidan Doherty Dec 20 '22 at 23:53

0 Answers0