React native 已有项目升级兼容web

这篇具有很好参考价值的文章主要介绍了React native 已有项目升级兼容web。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

基础 

React native 已有项目升级兼容web,react native,react.js,javascript 概念 | webpack 中文文档 | webpack 中文文档 | webpack 中文网

 深入理解Webpack及Babel的使用 - 掘金

Introduction to React Native for Web // React Native for Web

Webpack 是一个现代的 JavaScript 应用程序的静态模块打包工具,它将应用程序所依赖的各种资源(js、css、图片等)视为模块,通过 loader 转换这些模块,最后打包成符合生产环境部署的静态资源。

Webpack 的运行机制基于一条简单的原则:一切文件皆模块。因此,Webpack 在构建应用程序时,会先从入口模块开始递归解析模块依赖,然后通过 loader 处理各种类型的模块,最后打包成一个或多个浏览器可识别的静态资源。

Webpack 的基本配置包括 entry、output、module 和 plugins 四个部分。其中,entry 指定了入口模块,output 指定了输出目录和输出文件名,module 则用于配置 loader 和其他的一些规则,plugins 则是用于扩展 Webpack 功能的插件。

在使用 Webpack 进行项目开发时,我们通常需要使用 Babel 将 ES6+ 代码转换成浏览器兼容的 ES5 代码。Babel 的作用是将 JavaScript 新特性转换成浏览器支持的语法,例如箭头函数、解构赋值等。而 Loader 则是 Webpack 中用于处理各种类型文件的工具,例如将 css 转换成 JavaScript 对象、将图片转换成 data URL 等。

Babel是一个JavaScript编译器,可以将最新版本的JavaScript转换为向后兼容的代码,以便在旧版浏览器或其他环境中运行。Babel的作用是让我们使用最新的JavaScript语法特性,而不必担心浏览器是否支持这些特性。

过程

yarn add react-dom react-native-web
yarn add react-native-reanimated
yarn add -D babel-plugin-react-native-web
yarn add -D babel-loader url-loader webpack webpack-cli webpack-dev-server
yarn add -D babel-plugin-react-native-web
#每次打包发布时自动清理掉 dist 目录中的旧文件,
yarn add -D clean-webpack-plugin


#html-webpack-plugin的主要作用就是在webpack构建后生成html文件,同时把构建好入口js文件引入到生成的html文件中。
yarn add -D html-webpack-plugin



webpack.config.js

const path = require('path');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');

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',
].map((moduleName) => path.resolve(appDirectory, `node_modules/${moduleName}`));

const baseProjectSource = [
  path.resolve(appDirectory, 'web/index.web.js'), // Entry to your application
  path.resolve(appDirectory, 'web/App.web.js'), // Change this to your main App file
  path.resolve(appDirectory, './src'),
];


const babelLoaderConfiguration = {
  test: /\.(js|jsx|ts|tsx)$/,
  // Add every directory that needs to be compiled by Babel during the build.
  include: baseProjectSource,
  use: {
    loader: 'babel-loader',
    options: {
      cacheDirectory: true,
      // The 'react-native' preset is recommended to match React Native's packager
      presets: ['module:metro-react-native-babel-preset'],
      // Re-write paths to import only the modules needed by the app
      plugins: ['react-native-web', 'react-native-reanimated/plugin'],
    },
  },
};


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

module.exports = {
  entry: {
    app: path.join(appDirectory, 'web/index.web.js'),
  },
  output: {
    path: path.resolve(appDirectory, 'dist'),
    publicPath: '/',
    filename: 'upup.bundle.js',
  },
  resolve: {
    // If you're working on a multi-platform React Native app, web-specific
    // module implementations should be written in files using the extension
    // `.web.js`.
    extensions: ['.web.tsx', '.web.ts', '.tsx', '.ts', '.web.js', '.js'],
    alias: {
      'react-native$': 'react-native-web',
    },
  },
  module: {
    rules: [
      babelLoaderConfiguration,
      imageLoaderConfiguration,
    ],
  },
  devServer: {
    port: 8080,
    historyApiFallback: true,
    open: !process.env.CI,
  }, 
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [
        '**/*'
      ]
    }),
    // `process.env.NODE_ENV === 'production'` must be `true` for production
    // builds to eliminate development checks and reduce build size. You may
    // wish to include additional optimizations.
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      __DEV__: process.env.NODE_ENV === 'production' || true
    }),
    new HtmlWebpackPlugin({
      template: path.join(appDirectory, 'web/index.html'),
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
      // See: https://github.com/necolas/react-native-web/issues/349
      __DEV__: JSON.stringify(true),
    }),
  ],
};

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>RN Web</title>
    <style>
      #app-root {
        display: flex;
        flex: 1 1 100%;
        height: 100vh;
      }
    </style>
  </head>
  <body>
    <div id="app-root"></div>
  </body>
</html>

index.web.js

import {AppRegistry} from 'react-native';
import appInfo from '../app.json';
import App from './App.web';


AppRegistry.registerComponent(appInfo.name, () => App);
AppRegistry.runApplication(appInfo.name, {
  initialProps: {},
  rootTag: document.getElementById('app-root'),
});

App.web.js


import React from 'react';
import FaqTestnet from '../src/screen/FaqTestnet';
import AboutTestnet from '../src/screen/AboutTestnet';
import 'react-native-gesture-handler';
import {NavigationContainer} from '@react-navigation/native';
import {
  createStackNavigator,
  CardStyleInterpolators,
} from '@react-navigation/stack';
import Color from "../src/app/Color";
import DarkTheme from '../src/app/DarkTheme';

const Stack = createStackNavigator();

const config = {
  screens: {
    FaqTestnet: 'faqtestnet',
    AboutTestnet: 'abouttestnet',
  },
};

const linking = {
  prefixes: ['http://tokshow.io',  'http://localhost:8080', 'http://127.0.0.1:5500/'],
  config,
};

function App() {
  return (
    <NavigationContainer linking={linking} fallback={<Text>Loading...</Text>} theme={DarkTheme}>
      <Stack.Navigator
        initialRouteName="AboutTestnet"
        screenOptions={{
          animationEnabled: false,
          headerShown: false,
          unmountOnBlur: false,
          cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        }}>
        <Stack.Screen
          name="FaqTestnet"
          component={FaqTestnet}
          options={{
            title: 'Testnet FAQ',
          }}
        />
        <Stack.Screen
          name="AboutTestnet"
          component={AboutTestnet}
          options={{
            title: 'About the Incentivized Testnet',
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

package.json

  "scripts": {
    "web:release": "export NODE_ENV=production && rm -rf dist/ && webpack --config ./webpack.config.js",
    "web": "export NODE_ENV=development && webpack-dev-server --config ./webpack.config.js",

参考

How to Make Your React Native Apps Work on the Web文章来源地址https://www.toymoban.com/news/detail-564111.html

到了这里,关于React native 已有项目升级兼容web的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • React Native Expo项目上传文件

              https://chat.xutongbao.top/ https://docs.expo.dev/versions/latest/sdk/document-picker/ https://blog.csdn.net/xutongbao/article/details/131981469?spm=1001.2014.3001.5501 

    2024年02月15日
    浏览(41)
  • React Native 集成到iOS原有的项目上

    集成到现有原生应用 把 React Native 组件集成到 iOS 应用中有如下几个主要步骤: 配置好 React Native 依赖和项目结构。 了解你要集成的 React Native 组件。 使用 CocoaPods,把这些组件以依赖的形式加入到项目中。 创建 js 文件,编写 React Native 组件的 js 代码。 在应用中添加一个RC

    2024年02月12日
    浏览(65)
  • 探索React Native认证实战示例项目:打造安全的移动应用体验

    项目地址:https://gitcode.com/hezhii/react-native-auth-example 在移动开发领域,React Native以其跨平台和高效性能而备受青睐。如果你正在寻找一个直观的、基于React Native的身份验证实现示例,那么这个项目—— react-native-auth-example ,将会是你的理想之选。 react-native-auth-example 是一个简单

    2024年04月27日
    浏览(30)
  • 重启React Native老项目的奇幻之旅:填坑实录与解决方案分享

    这两天为了重启五年前基于 React Native(版本 0.59.9)开发的老项目,经过各种填坑查询等操作,最终把它成功地运行起来了。 在这篇文章中,我将详述那些遭遇的挑战以及对应的解决方案,以期为同样面临此类困境的开发者提供宝贵的经验参考。 这个项目涉及到的环境基本版

    2024年04月16日
    浏览(28)
  • React Native expo项目使用expo-image-picker上传图片

     app.json: https://docs.expo.dev/versions/latest/sdk/imagepicker/      expo-image-picker 图片上传 要使用Expo的ImagePicker库进行图片上传,您可以按照以下步骤操作。 首先,确保您已在项目中安装了Expo的ImagePicker库。 然后,您可以使用以下代码来选择图片并上传: 此示例使用Button和Image组件创

    2024年02月15日
    浏览(30)
  • react-Native init初始化项目报错”TypeError: cli.init is not a function“

    在react-native init appDemo 创建项目时,报错TypeError: cli.init is not a function。 产生这个问题的原因是:使用这种方式创建工程,react-native版本是0.69 版本上不适用。可以检查下自己安装的React-native的版本。 使用: npx react-native init Demo --version 0.68.2 即可。 解决方法不好用的话,那就

    2024年02月15日
    浏览(32)
  • react native 0.73 配置 react-native-fs

    npm yarn android/settings.gradle android/app/build.gradle androidappsrcmainjavacomreactnative_demoMainApplication.kt 把原代码 改为

    2024年04月08日
    浏览(31)
  • React与React Native的异同

    开发React一段时间了,一直没有搞清楚React和React Native的差异。今天特意去了解下,发现差异还真不小! 相同点: 1.都是Facebook公司推出的框架。 2.都是基于JSX语言开发的。 差异点: 1、作用的平台不同. 2、工作原理不同. 3、渲染周期不同. 4、组件构成形式不同. 5、宿主平台的

    2024年02月06日
    浏览(30)
  • 探索React Native的世界:gorhom/react-native-animated-tabbar

    项目地址:https://gitcode.com/gorhom/react-native-animated-tabbar 在移动应用开发领域,React Native以其高效、跨平台的能力受到了广泛的欢迎。今天,我们要向您推荐一个极具创意且实用的React Native组件库——gorhom/react-native-animated-tabbar。它是一个精美设计的动画TabBar,为您的应用提供生

    2024年04月17日
    浏览(54)
  • 维护积极的react native,为什么会有人造谣react native不维护了,停止维护。

            其实近几年我一直关注react -native,他一直更新频繁,0.60大重构,升级了js执行引擎Hermes,当前已经0.70.4版本了。性能越来越提高,但是总感觉到有人在刷百度,只要输入react-native后面就自动提示热搜“react-native 停止维护”,这误导很多人以为真的不维

    2024年02月11日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包