react native 多平台配置,使用react-native-web运行在web端(自定义webpack.config.js配置篇)

前言

本文基于

  • “react-native”: “^0.72.4”
  • “react-dom”: “^18.2.0”
  • “react-native-web”: “^0.19.8”

本篇文章使用的自定义 webpack 配置的方式,配置起来相对麻烦一点

也可以参考另一篇文章,使用的是 react 官方提供的webpack配置包(react-scripts):react native 多平台配置,使用react-native-web运行在web端(react-scripts插件篇)

1.安装依赖

yarn add react-dom react-native-web babel-plugin-react-native-web --save

webpack相关

yarn add babel-loader url-loader webpack webpack-cli webpack-dev-server --dev

这个插件是官网没有提到的,算是一个坑

yarn add html-webpack-plugin --dev

2.配置 babel.config.js

官网 - 构建打包优化

plugins: ['react-native-web']

在这里插入图片描述

3.根目录新建 web/webpack.config.js

webpack配置在官网 - 多平台设置 ,复制到本地

在这里插入图片描述

4.配置 webpack.config.js

配置 html-webpack-plugin 插件

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
	...官网配置
	plugins: [
	  new HtmlWebpackPlugin({
	    template: path.resolve(__dirname, './index.html'), // 指定模板路径
	    filename: 'index.html', // 指定文件名
	    // favicon: path.resolve(appDirectory, 'web/favicon.ico') // 浏览器小图标
	  })
	]
}

配置 babelLoaderConfiguration

test: /\.js$|.tsx?$/,
path.resolve(appDirectory, 'App.tsx'),

test:需要由Babel编译的文件匹配规则
include:需要由Babel编译的文件、文件夹、插件包

react native 0.72.0版本开始,模板默认为 typescript 项目,需要添加.tsx
官方脚手架有一个App.tsx文件在根目录,而react-native-web官方提供的 webpack 配置并没有配置解析这个文件,需要添加到include

在这里插入图片描述

5.根目录新建 web/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 App</title>
</head>

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

在这里插入图片描述

6.根目录新建 index.web.js 文件

import { AppRegistry } from 'react-native';
import App from './App.tsx';

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

AppRegistry.runApplication('App', {
  rootTag: document.getElementById('root')
});

在这里插入图片描述

7.修改 App.tsx

import React from 'react';
import { Text } from 'react-native';

function App(): React.ReactElement {
  return <Text>Hello World</Text>;
}

export default App;

在这里插入图片描述

8.配置 package.json 启动命令

"web": "webpack serve --mode=development --config ./web/webpack.config.js",
"build": "webpack --mode=production --config ./web/webpack.config.js"

在这里插入图片描述

8.启动项目

web端

yarn web

在这里插入图片描述

在这里插入图片描述

app端

yarn android

在这里插入图片描述

如果本篇文章对你有帮助的话,很高兴能够帮助上你。

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

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值