Run your React Native app on the web with React Native for Web

“React Native for Web” makes it possible to run React Native components and APIs on the web using React DOM — allowing you to target the Android, iOS, and web platforms using a single codebase.

The React Native for Web documentation has a few examples of how to get started from scratch. For example, you can use expo or create-react-native-app to create a new React Native project compatible with React Native for Web. Or you can use Create React App to generate a simple, web-only React app with built-in support of React Native for Web.

In this post, I’d like to take a different approach from the one used in the React Native for Web documentation: I’ll explain how to add React Native for Web to an existing React Native app using Create React App.

Setup the Create React App project

The standard way to setup a React app from scratch using Create React App is by using the create-react-app CLI to generate the entire project. However, in our case, we’re adding a React app on top of an existing project, so the setup process will be a bit different.

Dependencies

First of all, let’s install these dependencies:

# If you're using NPM...
npm install react-native-web react-scripts react-dom

# ...or, if you're using Yarn
yarn add react-native-web react-scripts react-dom
  • react-native-web is the React Native for Web library. It provides a mapping of the React Native components and APIs to their web counterparts.
  • react-scripts are the scripts used by Create React App to bundle and run your web application.
  • react-dom is what allows React to run on the web. It’s recommended to install a version of React DOM that matches your currently installed version of React.

Directory Structure

Create React App expects your project to follow a specific directory structure.

Depending on how your current React Native setup looks like, you might need to make some changes to accommodate the Create React App convention.

The next steps will assume you’re starting with a directory structure similar to the following:

.
├── android/
│   └── ...
├── iOS/
│   └── ...
├── src/
│   ├── App.js # The root component of your React Native app
│   └── ...
└── index.js   # Where React Native's "registerComponent" is invoked

For the project to build, these files must exist with exact filenames:

  • public/index.html: The HTML page template served to the users. Create React App injects your React application in this page.
  • src/index.js: The JavaScript entry-point of your React web application.

Normally these files are generated by the create-react-app CLI… but since we couldn’t use it, we need to go a step further and create them manually.

The Public Directory

Create a new directory named public at the root of your project. In it, we will put the index.htmlfile and all the additional files that it uses.

To create its content, you can either a) copy and paste in the public directory the content of what the create-react-app CLI would have generated, or b) create just a minimal public/index.htmlfile like the following:

public/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title>Your App Title</title>
  </head>

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

The JavaScript Entry Point

Create a new index.js file in your src directory:

src/index.js

import { AppRegistry } from "react-native";
import { App } from "./App.js";

const appName = "Your app name";

AppRegistry.registerComponent(appName, () => App);
AppRegistry.runApplication(appName, {
  // Mount the react-native app in the "root" div of index.html
  rootTag: document.getElementById("root"),
});

This is the entry point of the JavaScript code that will be injected in your HTML file.

You might have noticed that you now have two different index.js files — one at the root of your project, and one in the src directory.

The metro bundler — which is the JavaScript bundler that builds your React Native app — will use the index.js file that you already have at the root of your project for building the Android/iOS app.
Webpack — used under the hood by Create React App — will instead use the new src/index.js.

To be a bit more explicit on which JS index file is used on a specific platform, I’d suggest renaming the root index.js file to index.native.js. See the official React-Native documentation for more details on the platform-specific extensions.

Create The Build Scripts

To complete the Create React App setup, add two script to your package.json to build your web app:

package.json

 "scripts": {
+  "web:start": "react-scripts start",
+  "web:build": "react-scripts build",
 }

Running the Web App

You can now use npm run web:start to spin-up the development environment of your web app and npm run web:build to create a production build.
The default configuration of Create React App already aliases all react-native imports to react-native-web by default, so you won’t have to worry about manually having to swap them based on the target platform.

That said, unless you’re extremely lucky, you won’t be able to run your React Native app on the web on the first try…

Here’s a list of a few common issues you might face.

Fixing the Dependency Tree Warning

The first time you run your web app you’ll probably see the following warning in the console:

There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

  "babel-jest": "^26.6.0"

Don't try to install it manually: your package manager does it automatically.
However, a different version of babel-jest was detected higher up in the tree:

  /Users/username/workspace/YourProject/node_modules/babel-jest (version: 25.5.1)

Manually installing incompatible versions is known to cause hard-to-debug issues.

If you would prefer to ignore this check, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That will permanently disable this message but you might encounter other issues.

This warning shows up because React Native ships with a version of babel-jest (or other packages, depending on what your warning says) that is different from the one used by Create React App.

The warning itself will point you to several possible fixes.
The two options I would suggest you try are:

  • Ignore this check by adding SKIP_PREFLIGHT_CHECK=true to a .env file at the root of your project. This will force react-script to use the dependency versions set in your package.json instead of the ones required by Create React App. Most of the time these errors are caused by a slightly different version of babel-jest or jest that can still be compatible with the versions you were using in your React Native app — which is why this solution will likely work.
  • Or uninstall the incriminated dependencies and run again npm install or yarn install. This will make your React Native app use the dependencies shipped with Create React App.

Regardless of what choice you make here, this change is one of the things you should test for regressions when in the future you’ll update your project to a new version of React Native or react-scripts.

Resolve Native Module Conflicts

React Native for Web is compatible with many native modules that ship with React Native: Button, Views, TextInput, etc… will be automatically mapped to their web counterparts correctly when imported from react-native.
Unfortunately, using other external native libraries like react-native-sound or react-native-keep-awake can be a bit hit-and-miss because many native functionalities are not available on the web.

In these cases, your web app will fail to compile with errors such as Module not found.

The React Native “Platform Specific Code” documentation has some great tips on how you can run platform-specific code and solve these issues.

My suggestion is to abstract these native libraries in files with platform-specific extensions so that only the React Native bundler will import them.

For example, assuming you want to use the KeepAwake component exported by the react-native-keep-awake only in your React Native app you should create two files:

  • A file with the code that runs on the native app named KeepAwake.native.js that just acts as a proxy for the react-native-keep-awake library:
import KeepAwake from "react-native-keep-awake";
export default KeepAwake;
  • A file with the code that runs on the web named KeepAwake.js that exports a mock/empty component:
import { Fragment } from "react";
export default Fragment;

By following this strategy you can now import the module ignoring the extension (import KeepAwake from "./KeepAwake";). The right file will be picked up automatically by Create React App and by the React Native bundler.

You might already be familiar with the .android.js and .ios.js extension. This concept basically acts in the same way, differentiating the code that runs on the web from the one that runs your native app by suffixing the latter with the .native.js extension.

Customize Create React App

Eventually, you might need to customize your project beyond what Create React App allows you to do. Most of these customizations will probably be just slight changes to the Webpack and Babel configuration of Create React App where ejecting would be overkill — which is why you might wanna use something like react-app-rewired, customize-cra, or craco to apply these changes without ejecting.

One of the first few customizations you’ll want to apply to Create React App, is adding support for the __dev__ keyword on the web. The React Native bundler sets the global __dev__ variable to true in development mode when you work on your React Native app, while Create React App uses process.env.NODE_ENV to determine if the web app is running in development/production instead.

To have a unified development experience and make your web app aware of __dev__, we can use react-app-rewired + customize-cra to change the Create React App Webpack configuration, setting the __dev__ variable correctly.

Install the following dependencies:

# If you're using NPM...
npm install -S customize-cra react-app-rewired

# ...or, if you're using Yarn
yarn add customize-cra react-app-rewired

Then, create a config-overrides.js file at the root of your project. It will be used by react-app-rewired + customize-cra to apply customizations to Create React App:

config-overrides.js

const webpack = require("webpack");
const { override, addWebpackPlugin } = require("customize-cra");

module.exports = override(
  addWebpackPlugin(
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify(
        process.env.NODE_ENV || "development"
      ),
      // Add support for the __DEV__ global variable
      __DEV__: process.env.NODE_ENV !== "production",
    })
  )
);

To activate these customizations, update your existing calls to react-scripts in the package.json to use react-app-rewired instead:

package.json

  "scripts": {
-   "web:start": "react-scripts start",
+   "web:start": "react-app-rewired start",
-   "web:build": "react-scripts build",
+   "web:build": "react-app-rewired build",
}

TypeScript

Create React App supports TypeScript. If your React Native is written in TypeScript, you just need to make sure your .tsconfig follows the same rules used in the Create React App TypeScript template.

Conclusion

It’s true, creating a React Native for Web project might not be as easy as creating a web app.
But in some cases the effort is definitely worth it: at the end of the day, you’re still building a native app and a web app using a single codebase.
I think the setup complexity is definitely justified here.

Thanks @necolas for creating and maintaining React Native for Web.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容