所以从使用命令的 react-native 应用程序的基本安装开始
npx react-native init newProject
安装依赖
我使用 yarn 但对于 npm 是 npm i -D myLib 而不是 yarn add -D myLib
对于我们需要的反应:
yarn add react react-dom react-native-web
对于 Webpack,我们需要:
yarn add -D webpack webpack-cli babel-loader webpack-dev-server
Webpack 配置
在根文件夹中创建一个名为 webpack.config.js 的文件
一个名为 public 的文件夹是输出文件夹
//webpack.config.js
const path = require("path");
module.exports = {
entry: {
main: "./index.web.js",
},
mode: "development",
devtool: "inline-source-map",
devServer: {
writeToDisk: true,
liveReload: true,
},
module: {
rules: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: "babel-loader",
},
],
},
resolve: {
alias: {
"react-native": "react-native-web",
},
},
output: {
path: path.resolve(__dirname, "public"),
},
};
以及根文件夹中的 index.html
<!DOCTYPE html>
<html>
<head>
<title>Testing on the Web!</title>
<meta charset="utf-8" />
<meta content="initial-scale=1,width=device-width" name="viewport" />
</head>
<body>
<div id="react-native-app"></div>
<script type="text/javascript" src="/public/main.js"></script>
</body>
</html>
根目录下用于测试的 index.web.js
import React, {Component} from "react";
import {AppRegistry, StyleSheet, Text, View} from "react-native";
class ReactNativeWeb extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#142a3d",
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10,
color: "#ffffff",
},
});
AppRegistry.registerComponent("ReactNativeWeb", () => ReactNativeWeb);
AppRegistry.runApplication("ReactNativeWeb", {
rootTag: document.getElementById("react-native-app"),
});
脚本包.json
我们在 package.json 中添加一个命令来启动构建和 webpack 服务器
{
...
"scripts": {
...
"web": "webpack serve --progress --config webpack.config.js"
}
...
}
现在,启动命令
yarn web
从浏览器打开http://localhost:8080/
请注意,webpack 配置只提供 javascript 文件,您必须为其他文件类型添加规则