前言
本文基于
本篇文章使用的是 react 官方提供的webpack配置包(react-scripts),对于react很熟悉的会非常方便
也可以参考另一篇文章,使用的自定义webpack配置:react native 多平台配置,使用react-native-web运行在web端(自定义webpack.config.js配置篇)
1.安装依赖
yarn add react-dom react-native-web --save
react 官方提供的webpack配置包,参考react项目
yarn add react-scripts --save
2.根目录新建 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">
<meta name="theme-color" content="#000000">
<title>React Apptitle>
head>
<body>
<noscript>
You need to enable JavaScript to run this app.
noscript>
<div id="root">div>
body>
html>

3.根目录新建 src/index.web.js 文件
react-scripts 默认的 webpack 编译文件夹为 src 文件夹
在 src 目录下新建 index.web.js 做为web端的入口文件
import { AppRegistry } from 'react-native';
import App from './App.tsx';
AppRegistry.registerComponent('App', () => App);
AppRegistry.runApplication('App', {
rootTag: document.getElementById('root')
});

4.配置 App.tsx
根目录的 App.tsx 文件无法被 webpack 解析,移动至 src 目录下
import React from 'react';
import { Text } from 'react-native';
function App() {
return <Text>hello world</Text>
}
export default App;

5.配置 package.json 启动命令
eject 用于暴露 webpack 配置,比如需修改 index.html、index.web.js 入口文件的存放位置等
"web": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"

6.启动项目
web端
yarn web


app端
入口文件依旧是根目录的 index.js 文件,App.tsx 被移动至 src 目录下,所以需修改路径。
// index.js
import App from './src/App';
yarn android

如果本篇文章对你有帮助的话,很高兴能够帮助上你。
当然,如果你觉得文章有什么让你觉得不合理、或者有更简单的实现方法又或者有理解不来的地方,希望你在看到之后能够在评论里指出来,我会在看到之后尽快的回复你。