Giter Site home page Giter Site logo

mmazzarolo / react-native-universal-monorepo Goto Github PK

View Code? Open in Web Editor NEW
1.7K 32.0 149.0 4.23 MB

React Native boilerplate supporting multiple platforms: Android, iOS, macOS, Windows, web, browser extensions, Electron.

License: MIT License

JavaScript 21.58% TypeScript 10.99% Ruby 5.06% Objective-C 19.16% Starlark 1.86% Java 19.26% HTML 8.14% CSS 1.88% C++ 11.40% Shell 0.66%
react-native react electron react-native-web android ios windows macos

react-native-universal-monorepo's Introduction

React Native Universal Monorepo

An opinonated approach to supporting multiple platforms with React Native using a Yarn Workspaces monorepo.

Check out Running React Native everywhere for an in-depth guide on how and why I recommend trying out this approach if you're planning to support multiple platforms in your app.

 

Overview

This monorepo uses Yarn workspaces and TypeScript to support a modular React Native project.

The core idea is to isolate the JavaScript app code from the platform configurations (native code + the app bundlers like Metro and Webpack).
This isolation happens by using different workspaces: We have an app workspace for the JavaScript app code, a mobile workspace for the React Native mobile configuration, a macos workspace for the React Native macOS configuration, and so on.

We fully embrace Yarn nohoist to allow using different versions of React Native on each platform (which is recommended but not required), simplifying the adoption of new React Native updates.
Thanks nohoist, each platform workspace (mobile, macos, etc.) can depend on any React Native version, regardless of what version the other platform workspaces are using. For example, we can use [email protected] on the mobile app and [email protected] on the macOS app — as long as the JavaScript app code supports both versions.
This approach promotes gradual React Native updates over updates in lockstep.

For more details, check out "Running React Native everywhere: Yarn Workspaces monorepo setup".

⚠️ Please notice that I'm not saying this is the right way to do React Native monorepos. This is just an approach that I enjoy using on larger codebases :)

Supported platforms

  • Android (React Native 0.65)
  • iOS (React Native 0.65)
  • Windows (React Native 0.65)
  • MacOS (React Native 0.63)
  • Android TV (React Native 0.65)
  • tvOS (React Native 0.65)
  • Web (React Native 0.65)
  • Web - Browser Extension (React Native 0.65)
  • Web - Electron (React Native 0.65)
  • Web - Next.js (React Native 0.65)

Getting started

You can use this repo as a boilerplate, removing the workspaces of platforms that you don't need, or you can create this setup from scratch if you want to fully understand how it works.

Using this repository as a boilerplate

  1. Clone the repository: [email protected]:mmazzarolo/react-native-universal-monorepo.git
  2. Run yarn install cd react-native-universal-monorepo && yarn

Create this setup from scratch

Step by step tutorial on creating this repository from scratch:

Tutorial for the TV and Next.js platforms from @thefinnomenon:

Additional resources:

Available commands

Development and build commands:

  • yarn android:metro: Start the metro server for Android/iOS
  • yarn android:start: Start developing the Android app
  • yarn android:studio: Open the android app on Android Studio
  • yarn ios:metro: Start the metro server for Android/iOS
  • yarn ios:start: Start developing the iOS app
  • yarn ios:pods: Install iOS cocoapods dependencies
  • yarn ios:xcode: Open the iOS app on XCode
  • yarn macos:metro: Start the metro server for macOS
  • yarn macos:start: Start developing the macOS app
  • yarn macos:pods: Install macOS cocoapods dependencies
  • yarn macos:xcode: Open the macOS app on XCode
  • yarn web:start: Start developing the web app
  • yarn web:build: Create a production build of the web app
  • yarn electron:start: Start developing the Electron app
  • yarn electron:package:mac: Package the production binary of the Electron app for macOS
  • yarn electron:package:win: Package the production binary of the Electron app for windows
  • yarn electron:package:linux: Package the production binary of the Electron app for linux
  • yarn browser-ext:start: Start developing the browser extension
  • yarn browser-ext:build: Create a production build of the browser extension
  • yarn windows:metro: Start the metro server for Windows
  • yarn windows:start: Start developing the Windows app
  • yarn tv:android:metro: Start the metro server for Android TV
  • yarn tv:android:start: Start developing the Android TV app
  • yarn tv:android:studio: Open the Android TV app in Android Studio
  • yarn tv:tvos:metro: Start the metro server for tvOS
  • yarn tv:tvos:start: Start developing the tvOS app
  • yarn tv:tvos:xcode: Open the tvOS app in XCode
  • yarn tv:tvos:pods: Install tvOS cocoapods dependencies
  • yarn next:start: Start the Next.js app
  • yarn next:build: Build the Next.js app
  • yarn next:serve: Serve the Next.js app build

Other commands (we use ultra-runner to run these commands on all workspaces):

  • yarn lint: Lint each project
  • yarn lint:fix: Lint + fix each project
  • yarn test: Run tests of each project
  • yarn typecheck: Run the TypeScript type-checking on each project

Native dependencies

While working on React Native in a monorepo, you'll notice that several packages won't work correctly when hoisted — either because they need to be natively linked or because they end up being bundled twice, breaking the build (e.g., react, react-dom).
This is not an issue with the approach used in this project per se. It's more of a common problem with monorepos.

To fix these issues, we mark them as nohoist, so they will be installed in each package that depends on them.

In this monorepo, you can see an example of such libraries in react-native-async-storage.

In the metro bundler and Webpack configs used across the monorepo, we're using a set of build-tools to ensure nohoisted packages are resolved correctly.
So, as long as you add these libraries to the nohoist list, you should be good to go 👍

Yarn Classic vs Yarn 2+

We're striving to make this setup compatible with Yarn Classic — but, with a few tweaks, it's compatible with Yarn 2+ as well (providing all Yarn 2+ benefits).
See #22 for more info.

Setting up Yarn 2+

  1. Run yarn set version berry at the root of project. It will create a .yarnrc.yml file.
  2. Add the following lines to .yarnrc.yml to ensure node_modules directories are all created in each workspace:
nodeLinker: node-modules
nmHoistingLimits: workspaces
  1. nmHositingLimits tells how to hoist dependencies for each workspace. By setting it to workspaces all dependencies will be installed in each workspace's node_modules rather than being hoisted to the root folder. This means you can now you can safely the noHoist section in the root's package.json.

Check out Yarn 2+'s "getting started" guide for more info.

Known issues

In some cases, Yarn Classic won't be able to resolve correctly dependencies that have a peerDependency on react-native.
See #22 for a few workarounds. A fix on the react-native-monorepo-tools repo is on the work.

Contributing

Contributions, discussions, and feedback are welcome! Please ask if there are any active plans on feature changes before submitting new PRs 👍

react-native-universal-monorepo's People

Contributors

chakrihacker avatar code4break avatar kthompson avatar laikmosh avatar mmazzarolo avatar stigi avatar thefinnomenon avatar timolins avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-universal-monorepo's Issues

Upgrade to yarn 3

One big problem yarn 2 and above versions is noHoist

nodeLinker: node-modules
nmHoistingLimits: workspaces

with this kind of configuration. each workspace/package will have it's own dependencies.

Pros: No more dependency hassles
Cons: Duplicated dependencies with more disk space.

I can raise a pr if you want to consider upgrading yarn

Webpack error on Windows

Hello, first of all thank you very much for this guide. It was really good. But I'm stuck at one place. After completing the mobile and web installations, I get an error when I start it with "yarn web:start".
I've created a repository and added the error screenshot to readme.md so you can test the faulty code.

https://github.com/OkancanCosar/react-personal-monorepo

Thank you for your help :)

Dependencies, that have `react-native` as a `peerDependency`, resolve to the wrong version of `react-native`

Thanks for such a great monorepo setup

It works great out of the box, but as soon as i started to add dependencies, that use react-native, it stopped working for me.

I tried all combination of nohoist and resolutions, but i was not able to set version of nested react-native dependency of dependencies of platforms. Any hints?

Typescript webapp errors on non-web files

First of all, sorry for the issue title but that was the most accurate thing I was able to write.

I'm porting my current monorepo to this awesome setup and I'm facing some new issues that I didn't have before. For some features, I have two different files (in the same folder) one called index.ts and index.web.ts and based on what react-native-web defines on their docs, it should read the *.web.ts on the web and the other file on the rest of the platforms.

This react-native-web feature was working fine before, but now I'm getting some typescript errors from the non web file on the web platform.

I'm not sure if there is something specific that needs to be done in order to enable this feature in this monorepo setup.

Thank you very much,

Eric.

Built Electron app opens with white screen when using electron-builder

I'm not entirely sure whether this has something to do with the Electron configuration in the universal-monorepo tutorial, or whether extra steps need to be taken because of files being outside of the src folder in the Electron app, but hoping to get some pointers here if possible.

I am building the Electron app with electron-builder. The app builds fine itself but will only display a blank screen. This is a widely documented issue with the build path being incorrect in the Electron configuration, but it seems fine to me and in line with what people suggest works.

Here is the package.json in my Electron package:

{
	"name": "@my-app/electron",
	"description": "my-app description",
	"version": "0.1.0",
	"author": "my-app",
	"private": true,
	"homepage": "./",
	"main": "./public/electron.js",
	"dependencies": {
		"firebase": "^9.2.0",
		"react": "^17.0.2",
		"react-dom": "^17.0.2",
		"react-native-web": "^0.17.5",
		"react-scripts": "4.0.3",
		"uuid": "^8.3.2",
		"web-vitals": "^1.0.1"
	},
	"scripts": {
		"cra:start": "craco start",
		"cra:build": "craco build",
		"start": "concurrently -k \"cross-env BROWSER=none yarn cra:start\" \"wait-on http://localhost:3000 && electronmon .\"",
		"build": "craco build",
		"test": "react-scripts test",
		"eject": "react-scripts eject",
		"dist": "electron-builder"
	},
	"eslintConfig": {
		"extends": [
			"react-app"
		]
	},
	"browserslist": {
		"production": [
			">0.2%",
			"not dead",
			"not op_mini all"
		],
		"development": [
			"last 1 chrome version",
			"last 1 firefox version",
			"last 1 safari version"
		]
	},
	"devDependencies": {
		"@craco/craco": "^6.3.0",
		"@types/jest": "^26.0.15",
		"@types/node": "^12.0.0",
		"@types/react": "^17.0.0",
		"@types/react-dom": "^17.0.0",
		"@types/uuid": "^8.3.1",
		"concurrently": "^6.3.0",
		"cross-env": "^7.0.3",
		"electron": "^15.2.0",
		"electron-builder": "^22.14.5",
		"electronmon": "^2.0.2",
		"react-native-monorepo-tools": "^1.1.1",
		"wait-on": "^6.0.0"
	},
	"build": {
		"extends": null,
		"appId": "com.my-app.my-app",
		"productName": "my-app",
		"directories": {
			"output": "dist"
		},
		"mac": {
			"target": "pkg",
			"darkModeSupport": "true",
			"extendInfo": "my-app"
		},
		"pkg": {
			"installLocation": "/Applications",
			"overwriteAction": "upgrade"
		},
		"extraFiles": [
			"../app/src/"
		]
	}
}

my electron.js:

// Module to control the application lifecycle and the native browser window
const { app, BrowserWindow } = require('electron');
const path = require('path');
const url = require('url');

// Create the native browser window.
function createWindow() {
	const mainWindow = new BrowserWindow({
		width: 800,
		height: 600,
		webPreferences: {
			preload: path.join(app.getAppPath(), 'preload.js'),
		},
	});

	// In production, set the initial browser path to the local bundle generated
	// by the Create React App build process.
	// In development, set it to localhost to allow live/hot-reloading.
	const appURL = app.isPackaged
		? url.format({
			// @ts-ignore
			pathname: path.join(__dirname, 'index.html'),
			protocol: 'file:',
			slashes: true,
		})
		: 'http://localhost:3000';
	console.log('appURL -------------------->', appURL); // does not log
	mainWindow.loadURL(appURL);

	// newbedev.com/how-to-set-electron-useragent
	// mainWindow.webContents.userAgent = 'Chrome';
	// Automatically open Chrome's DevTools in development mode.
	if (!app.isPackaged) {
		mainWindow.webContents.openDevTools();
	}
}

// This method will be called when Electron has finished its initialization and
// is ready to create the browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
	createWindow();

	app.on('activate', () => {
		// On macOS it's common to re-create a window in the app when the
		// dock icon is clicked and there are no other windows open.
		if (BrowserWindow.getAllWindows().length === 0) {
			createWindow();
		}
	});
});

// Quit when all windows are closed, except on macOS.
// There, it's common for applications and their menu bar to stay active until
// the user quits  explicitly with Cmd + Q.
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

app.setAsDefaultProtocolClient('my-app');

In the above file, I do not see any of the console.logs in the electron console. I'm using TypeScript in the rest of the app. Any ideas much appreciated.

Global type definitions are not recognized

Using type definitions from global.d.ts file in the app directory causes web/electron app to crash. VS Code doens't complain.

Tried adding the directory to tsconfig.json in typeroots and/or include but no luck.

Web-based `build` commands fail because of `AsyncStorage`

Hello, thanks for you great work :)

I got this error on build web

~: yarn web:build
yarn run v1.22.10
$ yarn workspace @rnup/web build
$ craco build
Creating an optimized production build...
Failed to compile.

./node_modules/@react-native-async-storage/async-storage/lib/module/AsyncStorage.js
Attempted import error: 'merge-options' does not contain a default export (imported as 'mergeOptions').


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed.
Exit code: 1
Command: /usr/local/Cellar/node/16.4.2/bin/node
Arguments: /usr/local/Cellar/yarn/1.22.10/libexec/lib/cli.js build
Directory: /Users/***/react-native-universal-monorepo/packages/web
Output:

info Visit https://yarnpkg.com/en/docs/cli/workspace for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
~:

How to globally rename the project?

Thank you for this excellent boilerplate. I wondered if there is a one-liner or a bash script that helps renaming the project from ReactNativeUniversalProject to something else. I actually only require iOS and Android builds if this matters. I am honestly not sure if this is something I can do from the Terminal/VSCode or if I have to run XCode when it comes to the iOS-Build. Any suggestion would be appreciated.

Greets
-act

Local image file .png in ./app/src folder is not showing in windows build

Hi all, I have a encounter an issue with my windows build, the Image cannot be shown from the ./app/src/Logo.png, just Blank and got this error from metro bundler, not sure if it's related, it's trying to resolve the my component in the node_modules and ....\node\node_modules, which does not exist there. Is it the path should be hoisted 2 more layers?

  • Windows 10 SDK 10.0.18372.0
  • Visual Studio Community 2019
├── node_modules
├── package.json
└── packages
    ├── @my-app/app
        ├── src
                 ├── Logo.png
    ├── @my-app/macos 
    ├── @my-app/windows

Error: Unable to resolve module ./app/src/presentation/ui/MainScreen from C:\Users\<project-folder>\packages\windows/.: ./app/src/presentation/ui/MainScreen could not be found within the project or in these directories:
  node_modules
  ..\..\node_modules

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*

Typescript errors in node_modules

Hey everyone! I'm porting my current monorepo to this awesome setup and I'm facing some new issues that I didn't have before. I have some 3rd party libraries installed in my repo and I'm getting some errors on those libraries' code that I didn't have before.

The thing is that even though I have my node_modules folder excluded from transpiling within my tsconfig.json file (the same way you did), I'm still getting typescript errors from those libraries.

You can replicate this issue just by cloning your repo and installing react-native-linear-gradient or react-native-dialog in the app package, add some usage in the App.tsx file and then start the web package. You will see something like:

image

image

image

image

image

I don't know if I have to configure babel in a certain way in order to make this error disappear, but my previous monorepo was also using a CRA scaffold for the web package and I was not getting any of this errors.

Thank you very much,

Eric.

Module not found: Error: You attempted to import react which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

Compiled with problems:X

ERROR in ../app/src/index.js 5:0-85

Module not found: Error: Can't resolve 'react-native' in 'C:\wamp64\www\goolaMonoRepo\packages\app\src'

ERROR in ./src/index.js 4:0-26

Module not found: Error: You attempted to import C:\wamp64\www\goolaMonoRepo\packages\web\node_modules\react which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.
You can either move it inside src/, or add a symlink to it from project's node_modules/.0

Failed to compile when upgrading react-scripts to 5.0.0.

Hi,

we are trying to upgrade react-scripts (CRA) from 4.0.3 to 5.0.0 (CRA5). This is mainly due to High risk vulnerabilities within the following dependencies:

ansi-html-0.0.7.tgz
node-forge-0.10.0.tgz
com.google.code.gson-gson-2.8.0.jar
browserslist-4.14.2.tgz
url-parse-1.5.4.tgz
css-what-3.4.2.tgz
ansi-regex-3.0.0.tgz
nth-check-1.0.2.tgz
immer-8.0.1.tgz
follow-redirects-1.14.7.tgz
glob-parent-3.1.0.tgz
ejs-2.7.4.tgz
jdom2-2.0.6.jar

As CRA5 has already or will update these dependencies, we have to upgrade as well due to our internal policies.
When just using react-scripts 5.0.0 (web), we got

Failed to compile.

Module not found: Error: You attempted to import C:\Temp\React-native-universal-monorepo\react-native-universal-monorepo\packages\web\node_modules\react-dom which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

As we thought, this might be depended on CRACO addressing Webpack5 as well, we tried to update craco to 7.0.0-alpha.3 but this resulted in the same compiler error.

So my question is, due have any information on how to use CRA5 with RNUM or do you have any plans to upgrade this to CRA5 in the future? Any help /information is apprciated!

Thanks

Guido

Project license

I noticed the project is unlicensed. Do you plan to release it under an open source license? A good reference for choosing a license that meets your needs can be found at choosealicense.com. For a template project like this MIT or a similar permissive license might make a good option.

Webpack has been initialised using a configuration object that does not match the API schema

Hi all! I'm just starting with react-native. I installed a repo on all the instructions. However, when starting
PS C:\Projects\react-native-universal-monorepo-master> yarn web:start
An error arises:

Failed to compile.
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.

  • configuration.module.rules[1].oneOf[2].include should be one of these:
    RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? } | [RegExp |
    string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
    -> One or multiple rule conditions
    Details:
    • configuration.module.rules[1].oneOf[2].include[1]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/app/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[2]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/browser-ext/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[3]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/electron/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[4]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/macos/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[5]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/mobile/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[6]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/next/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[7]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/tv/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[8]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/web/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[9]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/windows/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[1]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/app/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[2]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/browser-ext/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[3]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/electron/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[4]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/macos/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[5]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/mobile/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[6]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/next/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[7]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/tv/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[8]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/web/" is not an absolute path!
    • configuration.module.rules[1].oneOf[2].include[9]: The provided value "C:/Projects/react-native-universal-monorepo-master/packages/windows/" is not an absolute path!

I could not find solutions myself. Perhaps the solution is somewhere here?:

file get-webpack-tools.js :
const workspaces = getWorkspaces({ cwd });
function enableWorkspacesResolution(webpackConfig) {
const babelLoader = webpackConfig.module.rules[1].oneOf.find((rule) =>
rule.loader.includes("babel-loader")
);
babelLoader.include = Array.isArray(babelLoader.include)
? babelLoader.include
: [babelLoader.include];
for (const workspace of workspaces) {
babelLoader.include.push(workspace);
}

file get-workspaces.js :
const monorepoRoot = getMonorepoRoot({ cwd });
const packageJson = require(path.join(monorepoRoot, "package.json"));

Thanks!

Next + Native-Base error

Hello there! We are trying to use this monorepo to have a project with RN for mobile part and Next.js + NativeBase for the web. The issue that after we installed NativeBase in monorepo we got an errors and we think that the problem is lying somewhere in monorepo setup. BTW RN + NativeBase in monorepo works fine. To understand the issue we also tryed to run a new project (outside monorepo) with Next+NativeBase setup and thats works fine! Could you please give us a hint how to solve that issue, will be really appreciate for this

Error looks like:

Screenshot 2022-01-21 at 18 12 39

This is our next config, with integrated config from NativeBase docs (https://docs.nativebase.io/install-next)

const withImages = require("next-images");

const withFonts = require("next-fonts");
const withTM = require("next-transpile-modules")([
  "react-native-web",
  "native-base",
]);
const { withExpo } = require("@expo/next-adapter");

module.exports = withTM(
  withExpo(
    withImages(
      withFonts({
        typescript: {
          ignoreBuildErrors: true,
        },
        experimental: {
          externalDir: true,
        },

        images: {
          disableStaticImages: true,
        },
        webpack: (config, options) => {
          config.module.rules.push({
            test: /\.mobile.(ts|tsx)$/,
            loader: "ignore-loader",
          });

          if (options.isServer) {
            config.externals = [
              "react",
              "react-native-web",
              ...config.externals,
            ];
          }
          config.resolve.alias["react"] = path.resolve(
            __dirname,
            ".",
            "node_modules",
            "react"
          );
          config.resolve.alias["react-dom"] = path.resolve(
            __dirname,
            ".",
            "node_modules",
            "react-dom"
          );
          config.resolve.alias["react-native-web"] = path.resolve(
            __dirname,
            ".",
            "node_modules",
            "react-native-web"
          );

          return config;
        },
      })
    )
  )
);

### INFORMATION

  1. We try to use 11.x.x and 12.0.4 next versions (Because of expo webpack5 support we tryed a different next versions)
  2. To integrate NativeBase we create a new directory(inside monorepo) and install NextJS with NativeBase (https://docs.nativebase.io/install-next) from scratch - not work
  3. Also tryed to install NativeBase into existing NextJS project - got the same errors as for step 2

Docker run cannot find package json

Hi, I was able to run yarn web:start from CMD. However when I try to run this in Docker. I got package.json not found error.
Here is the docker file:

FROM node:16.13.0-alpine

set working directory

WORKDIR /
COPY ["yarn.lock", "package.json", "./"]
RUN yarn reset:unix
RUN yarn

add app

COPY . ./

start app

CMD ["yarn", "web:start"]

After successful docker build, I try to run in docker desktop:
docker run -p:3000:3000 myimage
I got this error:
yarn run v1.22.15
$ yarn workspace @my-app/web start
$ craco start
/node_modules/find-root/index.js:19
throw new Error('package.json not found in path')
^

Error: package.json not found in path
at findRoot (/node_modules/find-root/index.js:19:11)
at findRoot (/node_modules/find-root/index.js:28:10)
at findRoot (/node_modules/find-root/index.js:28:10)
at findRoot (/node_modules/find-root/index.js:28:10)
at findRoot (/node_modules/find-root/index.js:28:10)

Any idea on this?
Thanks for the help

Cannot resolve peer dependency 'react' (or 'react-native)

Hi all,
After cloning the repo and installing with yarn I tried to simply launch the Android app using yarn android:start.
However, the app launches with an error (see below).

My assumption is that this has to do with the nature of peer dependencies in the app package.
If I remove the react import from .../packages/app/src/App.tsx the same error occurs with react-native.

Somehow, the bundler does not use the react/react-native packages provided in the node_modules of the mobile package.
Did I forget to do something or is this a bug?

I am using yarn 1.22.18

error: Error: Unable to resolve module react from C:\Users\Username\Git\react-native-universal-monorepo\packages\app\src\App.tsx: react could not be found within the project or in these directories:
  ..\app\node_modules
  ..\..\node_modules

If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*

1 | import React from "react";
  |                    ^
2 | import {
3 |   Image,
4 |   ImageSourcePropType,
    at ModuleResolver.resolveDependency (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:129:15)
    at DependencyGraph.resolveDependency (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\node-haste\DependencyGraph.js:288:43)
    at Object.resolve (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\lib\transformHelpers.js:129:24)
    at resolve (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\DeltaBundler\traverseDependencies.js:396:33)
    at C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\DeltaBundler\traverseDependencies.js:412:26
    at Array.reduce (<anonymous>)
    at resolveDependencies (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\DeltaBundler\traverseDependencies.js:411:33)
    at processModule (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\DeltaBundler\traverseDependencies.js:140:31)
    at async addDependency (C:\Users\Username\Git\react-native-universal-monorepo\packages\mobile\node_modules\metro\src\DeltaBundler\traverseDependencies.js:230:18)
    at async Promise.all (index 0)

Fix build/script script names in electron

When I run yarn electron:package:mac I get the error "Command "build" not found". When I update the packages/electron package.json script to remove yarn build from the "package:mac" script, electron build throws the error: "Application entry file "build/electron.js in Contents/Resources/app.asar" does not exist".

Is there a way to resolve this? Thanks.

Adding react-native-vector-icons

rnvi works without being in a monorepo, but when it is in one it throws this:

You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
|       return (
>         <Text selectable={false} {...props}>
|           {glyph}
|           {children}

How did I test it? I tried importing a screen from the /packages/app with an icon in it and the error was shown. When I put the screen directly into the /packages/next/pages/index.tsx file it works perfectly

Here is my next.config.js file

/** @type {import('next').NextConfig} */
const path = require("path");

const withPlugins = require('next-compose-plugins')
// Necessary to handle statically imported images
const withImages = require('next-images');
// Necessary to handle statically imported fonts
const withFonts = require('next-fonts');

const withTM = require('next-transpile-modules')([
	// 'react-native-paper',
	'react-native-vector-icons',
  'react-native-svg'
],{resolveSymlinks:true});




module.exports = withPlugins(
  [
    withTM, withFonts, withImages,
  ],
  {
      devIndicators: {
        autoPrerender: false
      },
      enableSvg: true,
      // Allows us to access other directories in the monorepo
      experimental: {
        externalDir: true,
        // concurrentFeatures: true,
      },
      // This feature conflicts with next-images
      images: {
        disableStaticImages: true,
      },
      webpack: (config, options) => {
        config.resolve.alias = {
          ...(config.resolve.alias || {}),
          // Transform all direct `react-native` imports to `react-native-web`
          'react-native$': 'react-native-web',
          'recyclerlistview$': 'recyclerlistview/web',
        }
        config.resolve.extensions = [
          '.web.js',
          '.web.ts',
          '.web.tsx',
          ...config.resolve.extensions,
        ]

        if (options.isServer) {
          config.externals = ['react', 'react-native-web', ...config.externals];
        }
        config.resolve.alias['react'] = path.resolve(__dirname, '.', 'node_modules', 'react');
        config.resolve.alias['react-native-web'] = path.resolve(__dirname, '.', 'node_modules', 'react-native-web');

        config.module.rules.push(
          {
            test: /\.(jpe?g|png|gif|svg)$/i,
            use: [ 'url-loader?limit=10000', 'img-loader' ]
          },
          {
            test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
            exclude: /node_modules/,
            use: [
              {
                loader: 'url-loader',
              }
            ],
            include: path.resolve(__dirname, '../app/node_modules/react-native-vector-icons')
            }
        )

        return config;
      }
 
  }
)

Add `.nvmrc` and set package `engine`

base λ yarn
yarn install v1.22.10
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version ">=14.0.0". Got "12.19.1"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Integrating Native-Base

Hi,
First of all kudos to the maintainer you've done an awesome job. We're trying to integrate Native-Base in this project but we want this to reside under "my-app/app" space so we could share components based on native-base between web and mobile. After installing native-base under mentioned space "my-app/app" it says that cannot find module react-native
image
/packages/app/src/components/Button.js

// import React from "react"
import { Button, Center, NativeBaseProvider } from "native-base"
function Button(){
  return (
    <>
      <Button onPress={() => console.log("hello world")}>Primary</Button>
    </>
  )
}
export default Button;

Add Next support

I have been trying to add a package for Next.js but am running into two issues.

  1. The Next app starts and runs fine except it doesn't show the image from the app.
    image

  2. At some point when I setup the Next package, it breaks the other web based packages; web, browser-ext, and electron. When I try to run them I get the following error,

Failed to compile.

../core/src/App.tsx
Module not found: Can't resolve 'react-native' in '<path>/<to>/packages/core/src'

There were some other annoying things like Next seemingly refusing to inject DEV and a weird error about hook usage but I came up with solutions for those.

Sorry if you aren't interested in using Next but figured I would see if you have any insight -- this monorepo stuff is so confusing 😖.

Here is the working branch https://github.com/thefinnomenon/universal-project-template/tree/feat-next

Enhancement: NX workspace plugin

This would suit an NX workspace plugin, we would fully benefit from the entire NX build caching system, vscode plugins, and also dependency update management system with migrations. Yarn is great, but NX is way more advanced.

https://nx.dev/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.