繁体   English   中英

如何将 react-native web 集成到现有的 React Native 项目中

[英]How to integrate react-native web to an existing react native project

我们有一个 react-native 项目使用typescriptreact-navigationreact-native-gesture-handlerredux/toolkit作为主要包实现

最近我们将 react-native-web 集成到我们的项目中,但它运行不正确。

我们的项目有几个问题:

  1. 导入自定义模块时无法加载它们。 例如:

     import MyCustomComponent from './components/MyCustomComponent' <View style={{flex: 1, backgroundColor: 'green'}}> <MyCustomComponent/> <--- does not show up, event when it contains a simple View component, we will see a blank screen </View>

    但是当我在当前文件中定义MyCustomComponent时,它显示没有问题:

     function MyCustomComponent() { return( <View style={{flex:1, backgroundColor: 'yellow'}}></View> ) } export default function MyMainComponent() { return ( <View style={{flex:1, backgroundColor: 'green'}}> <MyCustomComponent/> <---- this shows up </View> ) }
  2. redux Provider中的任何内容都不会再出现。

我认为我们的webpack配置是错误的,但由于我不是 web 开发方面的专家,我需要一些帮助来找出问题所在。 这是我们的 webpack 配置:

const path = require('path');

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

const appDirectory = path.resolve(__dirname);
const {presets} = require(`${appDirectory}/../babel.config.js`);

const compileNodeModules = [
  // Add every react-native package that needs compiling
  'react-native-gesture-handler',
  'react-redux',
  'react-native-reanimated',
  'react-native-confirmation-code-field',
  'react-native-calendars',
  '@react-native-google-signin/google-signin',
  'react-native-compressor',
  'react-native-swipe-gestures',
  '@react-native-async-storage',
  'react-native-shared-element',
  '@react-navigation',
  'react-native-material-menu',
  '@reduxjs/toolkit',
  'react-navigation-shared-element',
  'react-native-collapsible-tab-view',
  'react-native-image-crop-picker',
  '@react-native-community',
  'react-nativbe-safe-area-context/lib',
  'react-native-screens',
].map(moduleName =>
  path.resolve(appDirectory, `../node_modules/${moduleName}`),
);

const babelLoaderConfiguration = {
  test: /\.js$|tsx?$/,
  // Add every directory that needs to be compiled by Babel during the build.
  include: [
    path.resolve(__dirname, '../index.web.js'), // Entry to your application
    path.resolve(__dirname, '../src/index.web.tsx'), // Change this to your main App file
    path.resolve(__dirname, '../src'),
    ...compileNodeModules,
  ],
  use: {
    loader: 'babel-loader',
    options: {
      cacheDirectory: true,
      presets,
      plugins: ['react-native-web'],
    },
  },
};

const svgLoaderConfiguration = {
  test: /\.svg$/,
  use: [
    {
      loader: '@svgr/webpack',
    },
  ],
};

const tsLoaderConfiguration = {
  test: /\.(ts|tsx|web.ts|web.tsx)?$/,
  use: [
    {
      loader: 'ts-loader',
      options: {
        transpileOnly: true,
      },
    },
  ],
};

const imageLoaderConfiguration = {
  test: /\.(gif|jpe?g|png)$/,
  use: {
    loader: 'url-loader',
    options: {
      name: '[name].[ext]',
      esModule: false,
    },
  },
};

module.exports = {
  entry: {
    app: path.join(__dirname, '../index.web.js'),
  },
  output: {
    path: path.resolve(appDirectory, 'dist'),
    publicPath: '/',
    filename: 'arcelor.bundle.js',
  },
  resolve: {
    extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js'],
    alias: {
      'react-native$': 'react-native-web',
    },
  },
  module: {
    rules: [
      babelLoaderConfiguration,
      imageLoaderConfiguration,
      svgLoaderConfiguration,
      tsLoaderConfiguration,
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.join(__dirname, './index.html'),
      filename: 'index.html',
      inject: 'body',
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      // See: https://github.com/necolas/react-native-web/issues/349
      // __DEV__: JSON.stringify(true),
      __DEV__: process.env.NODE_ENV !== 'production',
      process: {env: {}},
    }),
  ],
};

我正在使用webpack@^5.65.0

谁能帮我找出问题所在以及如何使react-native-web与我们的项目一起使用? 谢谢

让 Webpack 从头开始运行并非易事。 我建议您从准备使用的方法开始,例如craexpo 然后按照自己的方式进行定制。

创建反应应用程序

  1. 首先,安装依赖项:
yarn add react-native-web react-scripts react-dom
  1. public/index.html中创建一个 HTML 文件并将以下内容放入: gh:facebook/create-react-app/cra-template
<!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>
  1. 将项目根目录中的index.js重命名为index.native.js

  2. src/index.js中创建一个 js 文件,并在里面放入以下内容:

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

AppRegistry.registerComponent(appName, () => App);
AppRegistry.runApplication("App", {
  rootTag: document.getElementById("root"),
});
  1. 通过运行react-scripts start运行应用程序

定制

您可能需要将诸如react-native-reanimated/plugin类的预处理器集成到您的 babel 配置中,或者编辑您的 WebPack 以添加诸如process.env之类的全局变量。 为此,您可以使用react-scripts eject来访问所述配置或使用custom-cra 之类的工具。

Expo(推荐)

看来,Expo 是最好的方法。 Expo 基本上是create-react-app但对于支持react-native-webreact-native

您可以按照官方指南为您的项目设置 web 的 expo。

  1. 安装依赖:
yarn add --global expo-cli
expo install react-native-web react-dom
yarn add expo
  1. 将您的根index.js修改为如下内容:
import { registerRootComponent } from 'expo';

import App from './App';

registerRootComponent(App);
  1. 此时您已准备好 go。 只是 rust expo start:web

定制

通过运行expo customize:web ,您可以访问 Babel 和 Webpack 配置文件。

Typescript basePath

如果您在tsconfig.json中使用"baseUrl": "src" 您可能还需要设置 Babel。 因为它可能不一定遵循您的 tsconfig。

// babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      'react-native-reanimated/plugin',
      [
        'module-resolver',
        {
          root: ['src'],
          extensions: ['.tsx', 'json', '.ts', '.js'],
        },
      ],
    ],
  };
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM