利用Webpack构建React Native for Web

项目演示

React Native for Web使得可以使用React DOM在Web上运行React Native组件和API。查看在Web上运行的React Native示例的实时演示。

快速开始

1.首先对于不太了解Webpack的同学可以先看一下这篇文章:https://segmentfault.com/a/1190000006178770

2.安装react-native-web npm i react-native-web

3.在webpack中配置react-native

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

/** __dirname是node.js中的一个全局变量,它指向当前执行脚本所在的目录 */
const appDirectory = path.resolve(__dirname, '../');

module.exports = {
  devtool: 'eval-source-map',//使用eval打包源文件模块,在同一个文件中生成干净的完整的source map。
  entry:  __dirname + "/app/main.js",//已多次提及的唯一入口文件
  output: {
    path: __dirname + "/public",//打包后的文件存放的地方
    filename: "bundle-[hash].js"//打包后输出文件的文件名
  },
  devServer: {
    contentBase: "./public",//本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    inline: true,//实时刷新
    hot: true
  },
  module: {
    rules: [
        {
          /** 正则表达式,编译所有.js文件 */
          test: /\.js$/,
          /** 包含要编译的目录和文件 */
          include: [
            /** 根目录下的index.js */
            path.resolve(appDirectory, 'index.js'),
            /** 子目录src下所有文件 */
            path.resolve(appDirectory, 'src'),
            path.resolve(appDirectory, 'node_modules/react-native-uncompiled')
          ]
        },
        {
            test: /(\.jsx|\.js)$/,
            use: {
                loader: "babel-loader",
            },
            exclude: /node_modules/
        },
        {
            test: /\.css$/,
            use: [
                {
                    loader: "style-loader"
                }, {
                    loader: "css-loader",
                    options: {
                       modules: {
                         localIdentName: "[name]__[local]--[hash:base64:5]" // 指定css的类名格式
                       }
                   }
                }, {
                     loader: "postcss-loader"
                }
            ]
        }
    ]
  },
    /**
   * resolve配置模块如何解析
   * */
  resolve: {
    alias: {
      'react-native$': 'react-native-web'
    },
    /** 自动解析确定的扩展 */
    extensions: ['.web.js', '.js'],
    /** 告诉webpack解析模块时应搜索的目录 */
    modules: ['node_modules']
  },
  plugins: [
       new webpack.BannerPlugin('版权所有,翻版必究'),
       new HtmlWebpackPlugin({
            template: __dirname + "/app/index.tmpl.html"//new 一个这个插件的实例,并传入相关的参数
        }),
        new webpack.HotModuleReplacementPlugin()//热加载插件
  ]
}

4.在项目中使用demo

import React, { Component } from "react";
import { Button, Image, StyleSheet, Text, View } from "react-native";

const logoUri = `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" /svg>`;

class App extends Component {
  render() {
    return (
      <View style={styles.app}>
        <View style={styles.header}>
          <Image
            accessibilityLabel="React logo"
            source={{ uri: logoUri }}
            resizeMode="contain"
            style={styles.logo}
          />
          <Text style={styles.title}>React Native for Web</Text>
        </View>
        <Text style={styles.text}>
          This is an example of an app built with{" "}
          <Link href="https://github.com/facebook/create-react-app">
            Create React App
          </Link>{" "}
          and{" "}
          <Link href="https://github.com/necolas/react-native-web">
            React Native for Web
          </Link>
        </Text>
        <Text style={styles.text}>
          To get started, edit{" "}
          <Link href="https://codesandbox.io/s/q4qymyp2l6/" style={styles.code}>
            src/App.js
          </Link>
          .
        </Text>
        <Button onPress={() => {}} title="Example button" />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  app: {
    marginHorizontal: "auto",
    maxWidth: 500
  }
});

export default App;

5.项目源码:https://github.com/243348167/react-native-web-sample

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要使用Webpack构建React应用,可以按照以下步骤进行操作: 1. 首先,在项目根目录下创建一个package.json文件,可以使用命令`npm init -y`快速创建。 2. 接下来,安装所需的依赖包。至少需要安装以下几个包:webpackwebpack-cli、babel-loader、@babel/core、@babel/preset-reactreact。 可以通过运行以下命令来安装这些包: ```shell npm install webpack webpack-cli babel-loader @babel/core @babel/preset-react react ``` 3. 在项目根目录下创建一个名为`webpack.config.js`的文件,用于配置Webpack。 在该文件中,至少包含以下内容: ```javascript const path = require('path'); module.exports = { entry: './src/index.js', // 入口文件 output: { path: path.resolve(__dirname, 'dist'), // 输出目录 filename: 'bundle.js' // 输出文件名 }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-react'] } } } ] }, resolve: { extensions: ['.js', '.jsx'] } }; ``` 上述配置中,entry指定了入口文件,output指定了输出目录和文件名,module.rules中的配置指定了Babel加载器的使用,resolve.extensions配置允许在导入模块时省略后缀名。 4. 在根目录下创建一个名为`src`的文件夹,并在其中创建一个`index.js`文件,作为React应用的入口文件。 ```javascript import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; // 你的React组件文件 ReactDOM.render(<App />, document.getElementById('root')); ``` 5. 创建一个名为`App.js`的文件,并在其中编写React组件的代码。 ```javascript import React from 'react'; function App() { return <h1>Hello, React!</h1>; } export default App; ``` 6. 最后,在命令行中运行以下命令来构建React应用: ```shell npx webpack ``` 这将会在项目根目录下创建一个`dist`文件夹,并在其中生成一个`bundle.js`文件。这个文件就是Webpack构建后的输出文件。 现在,你已经成功使用Webpack构建了一个基本的React应用。你可以根据需要进一步配置和优化Webpack,以满足项目的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖狗-小强

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值