现有Native项目的React Native启动

本文详细介绍了如何将React Native无缝集成到现有的iOS和Android原生项目中,包括项目结构、设置、本机模块、构建过程和CodePush。作者分享了个人经验,强调React Native可以减少开发时间,实现频繁更新和热重载,但也存在集成问题。建议开发者在尝试React Native时,先从小规模功能开始,逐步迁移。文章旨在为那些想要将React Native引入现有应用的开发者提供指导,帮助他们避免走弯路。
摘要由CSDN通过智能技术生成

React Native — the prodigal son for all mobile development! For a long while now I had been putting off my encounter with React Native just because of all the horror stories surrounding it. In the past few months I’ve been using it I formed a few opinions of my own regarding the SDK (remember these are just opinions and need to be taken with a pinch of salt and pepper and probably some marination.). In this article I would like to share these opinions and also help all you people out there who would want to integrate React Native into your existing app seamlessly so that you do not have to go through the process of trail and error before you actually have a screen built in React Native. This is not going to be a tutorial on React Native per se but will touch upon the other topics which are not so much talked about in terms of an existing native codebase.

React Native-所有移动开发的浪子! 很长一段时间以来,我一直因为与它有关的所有恐怖故事而推迟与React Native的会面。 在过去的几个月中,我一直在使用它,我对SDK形成了自己的一些见解(请记住,这些只是见解,需要用少量的盐和胡椒粉调味,也可能需要腌渍)。 在本文中,我想分享这些观点,还可以帮助所有想要将React Native无缝集成到现有应用程序中的人们,这样您就不必在实际使用前就经历了反复的过程。在React Native中内置的屏幕 这本来就不是React Native本身的教程,但将涉及其他话题,而这些话题在现有的本地代码库方面讨论不多。

This article will be broken down into the following sections:

本文将分为以下几节:

  1. Why React Native — I’ll be writing only the good parts here. The discussion on my opinions come later.

    为什么要使用React Native-在这里我只写优秀的部分。 关于我的观点的讨论将在稍后进行。
  2. Project structure — A little bit of git stuff and folder structures for smooth sailing.

    项目结构—一点点的git东西和文件夹结构,以使航行顺利。

  3. Project Setup — Includes a little description of how your react native setup should look like along with how your existing code-base will integrate it into their own project

    项目设置-包括一些有关本机设置的外观以及现有代码库如何将其集成到自己的项目中的描述
  4. Native Modules — just an introduction/few pointers on understanding it better.

    本机模块-只是介绍/很少有更好地了解它的指针。
  5. Build process — for development ,testing and release

    构建过程-用于developmenttestingrelease

  6. Codepush — Ship features out without doing an actual AppStore/PlayStore release.

    Codepush —在不进行实际AppStore / PlayStore发行的情况下发布功能。
  7. Opinions — This section is going to be my opinions on how my experience has been with React Native

    意见—本节将是我对我在React Native方面的经历的看法

This is going to be quite a long article, therefore I suggest you to take breaks while reading each section, otherwise it might feel like a lot to take in one reading since I touch on a lot of different topics while setting up the code-base. I would have loved to break the article into different parts but that felt like it would break the continuity. So if you’re ready ladies and gentlemen, get your coffee and let me take you on this adventure!

这将是一篇很长的文章,因此我建议您在阅读每一节时都要稍事休息,否则可能需要大量阅读,因为在设置代码库时我会涉及很多不同的主题。 我本来希望将文章分成不同的部分,但那感觉会破坏连续性。 因此,如果您准备好女士们和先生们,请喝杯咖啡,让我带您进行这次冒险!

为什么要使用Native? (Why React Native?)

You will find a lot of advantages mentioned by lots of people about React Native but I’m going to mention three advantages which really did strike a chord with me:

您会发现很多人提到了React Native的许多优点,但是我要提到的三个优点确实使我感到震惊:

  1. Decrease in shipping time — Since writing code in just one place leads to that feature being developed in both iOS and Android, just one developer is enough to develop the feature on both platforms, or if you’re just one developer working on both, this translates into you spending lesser time to develop that feature for both platforms.

    减少运输时间 -由于仅在一个地方编写代码会导致该功能同时在iOS和Android上开发,因此只有一名开发人员足以在两个平台上开发该功能,或者如果您只是一个在这两个平台上工作的开发人员,转化为您花费更少的时间来开发两个平台的功能。

  2. Frequent updates — Not to be confused with using it as a platform to ship untested code and ship bug fixes incrementally. This feature of the React Native is best used to be able to do frequent changes on layouts or features to make sure your business for the app grows. Keep your analytics ready for these features and using whatever data you collect for it to make changes so that you figure out what works best for your customer. Also genuine bug fixes should be shipped!

    频繁更新-不要与将其用作平台来交付未经测试的代码和逐步提供的错误修复相混淆。 最好使用React Native的此功能来对布局或功能进行频繁更改,以确保您的应用业务增长。 使分析准备好使用这些功能,并使用收集的所有数据进行更改,以便找出最适合客户的方法。 还应提供真正的错误修复程序!

  3. Hot reloading —This was pretty nifty when it came to making changes. No waiting for you to build the app before you can see your changes. Just save your file and voila!.

    热重装 -进行更改时非常漂亮。 在看到更改之前,无需等待您构建应用程序。 只需保存您的文件,瞧!

There were other advantages as well like the open source community being very active, performance being great, building modular components etc. but those points are either to be expected from the SDK(and the community has done an extremely good job of it) or these are things that you already find in our native development environments.

还有其他优势,例如开源社区非常活跃,性能出色,构建模块化组件等。但是,SDK可以期待这些观点(并且社区做得非常好)您已经在我们的本机开发环境中找到了这些东西。

项目结构 (Project structure)

Now given that you were already sold on the fact that you wanted to try out React Native I’m going to explain a little bit about the project structure that you should probably stick to. There are two ways you can go about integrating a React Native project into your existing native code bases:

现在考虑到您已经想尝试使用React Native了,因此,我将向您解释一些您可能应该坚持的项目结构。 您可以通过两种方式将React Native项目集成到现有的本机代码库中:

  1. Have your React-Native project as the root folder with two subfolders ios and android in it which contain your existing native code

    将您的React-Native项目作为根文件夹,其中包含两个子文件夹iosandroid ,其中包含您现有的本机代码

react-native-codebase
|- ios
|- android
|- other-react-native-codebase-files

2. Or Vice Versa. You maintain your native code bases separately and have the react native codebase inside the iOS and Android folders.

2.或Versa。 您可以分别维护本机代码库,并在iOS和Android文件夹中包含react本机代码库。

ios
|- ios-files
|- react-native-codebaseandroid
|- android-files
| - react-native-codebase

I tried both of these setups and I found the first one to be more seamless than the second one. The second approach even though it makes more logical sense if you want to maintain separate code bases since you do not know if you’re going to really move everything to react native, will end up giving you some integration problems for which you’ll probably have to write scripts etc. to make sure things like auto-linking and building the project works.

我尝试了这两种设置, 发现第一个比第二个更加无缝 。 第二种方法即使在您想要维护单独的代码库时更合乎逻辑,因为您不知道是否真的要移动所有内容来响应本机,最终会给您带来一些集成问题,您可能会为此付出代价。必须编写脚本等以确保诸如自动链接和构建项目等工作。

For example: the problems I faced with the second setup was that while building the project I had to write build scripts in my iOS codebase (android worked fine strangely) where I had to insert a build phase script to do some directory changes to make sure the the bundle was building properly.

例如:我在第二个设置中遇到的问题是,在构建项目时,我必须在iOS代码库中编写构建脚本(android的工作原理很奇怪,在其中),我必须插入构建阶段脚本以进行一些目录更改以确保捆绑包正确构建。

Auto-linking was also a problem in iOS. A little bit about auto-linking — Let’s say you’ve decided to use a react native library which has native code that needs to be integrated into your code base for you to use it(lots of libraries have it). For iOS you’d expect this to be integrated when you’re installing your pods and for android you’d want it to happen while you run your gradle sync. With the second setup, the iOS project was not able to auto-link the files properly from those libraries and I had to again spend some time to figure that out and fix it.

自动链接也是iOS中的问题。 关于自动链接的一些知识-假设您决定使用react本机库,该库具有本机代码,需要将本机代码集成到您的代码库中才能使用它(很多库都有它)。 对于iOS,您希望在安装Pod时将其集成;对于android,则希望在运行Gradle同步时实现。 在第二种设置下,iOS项目无法正确自动链接这些库中的文件,因此我不得不再次花费一些时间来找出并修复它。

Bottomline — Safe method is Method 1, but if you’re interested in having the second kind of structure you might have to go through some loops.

底线 -方法1是安全的方法,但是如果您对使用第二种结构感兴趣,则可能必须经历一些循环。

A little bit about the git structure — There are three ways here:

关于git结构的一些知识–这里有三种方式:

  1. Git Submodules

    Git子模块
  2. Git Subtrees

    Git子树
  3. Mono repo

    单声道回购

I’m not going to get into the debate of which is better and which is not. It all depends mostly on how you use it. There are definitely some advantages/disadvantages for all. Although I went with the submodule way. I did read a lot of hate for submodules but I really haven’t found it to be that bad (till now). You should do a little research on this before you decide on the git structure you would want to move ahead with.

我不打算讨论哪个更好,哪个更好。 这主要取决于您的使用方式。 肯定有一些优点/缺点。 尽管我采用了子模块方式。 我确实读了很多关于子模块的讨厌书,但是我真的没有发现它那么糟糕(到现在为止)。 在决定要继续使用的git结构之前,您应该对此做一点研究。

项目设置 (Project Setup)

Now that you have your folders structure in place, it’s time for you to setup your react native project. The major files that you need to know about here are:

现在您已经有了文件夹结构,是时候该设置您的本机项目了。 您需要在此处了解的主要文件是:

  1. package.json — Where you’ll write all your dependencies you need for your project.

    package.json —您将在其中编写项目所需的所有依赖项的位置。

  2. index.js — The file that is your entry point to the entire react-native code during runtime.

    index.js —在运行时,它是您整个本地代码的入口点的文件。

  3. metro.config.js — The file where you define the configuration for your metro bundler, that bundles your react-native js files. Ideally the default settings should work, but if you’re using the metro-react-native-babel-preset with non-default presets or have more transformers (eg: react-native-svg-transformer) then you might have to do a little more setup.

    metro.config.js —用于定义Metro bundler的配置的文件,该文件用于捆绑react-native js文件。 理想情况下,默认设置应该可以使用,但是如果您将metro-react-native-babel-preset与非默认预设一起使用,或者具有更多转换器(例如: react-native-svg-transformer ),则可能必须执行多一点的设置。

4. The rest of your files wile be your source code files which for which you can follow whatever folder structure you want.

4.您其余的文件将是您的源代码文件,您可以针对它们使用所需的任何文件夹结构。

变形金刚 (Transformers)

The metro config point might have gotten a little confusing which is why I shall try and explain transformers a bit more since you might encounter them a little more frequently than other things in your metro config file.

Metro配置点可能有点混乱,这就是为什么我将尝试解释一些变压器的原因,因为您可能比Metro配置文件中的其他事情更频繁地遇到它们。

Let’s start with Babel. Babel is a trans-compiler who’s job is to make sure whatever standard(ECMAScript 2015+) you write your JavaScript in it will make sure it works fine on all browsers (because different browsers/javascript engines might read js differently depending on the standard that they support) by making it backward compatible. By default metro has its own babel configuration setup and this should be enough for you.

让我们从Babel开始。 Babel是一位反编译器,他的工作是确保您使用JavaScript编写任何标准(ECMAScript 2015+),以确保它在所有浏览器上都能正常工作(因为不同的浏览器/ javascript引擎可能会根据不同的标准来读取js)他们支持),使其向后兼容。 默认情况下,Metro拥有自己的babel配置设置,这对您来说应该足够了。

Coming to transformers, they are an important part of how different types of files are transformed during bundling. I shall explain this with the help of an example and you can extrapolate it to different transformers like typescript transformers etc.

来到转换器时,它们是捆绑期间如何转换不同类型的文件的重要组成部分。 我将借助示例进行解释,您可以将其外推到不同的转换器,例如打字机转换器等。

Let’s use the simple case of react-native-svg-transformer. This library is used to transform .svg files for bundling so that they can be read by you JavaScript code during run time. Your files should look something like this in that case.

让我们使用react-native-svg-transformer的简单情况。 该库用于转换.svg文件以进行捆绑,以便您在运行时由JavaScript代码读取它们。 在这种情况下,您的文件应该看起来像这样。

You will have a metro.config.js file in your root directory with the following code:

您的根目录中将包含一个metro.config.js文件,其中包含以下代码:

/**
 * Metro configuration for React Native
 * https://github.com/facebook/react-native
 *
 * @format
 */


var path = require('path');
const { getDefaultConfig } = require('metro-config');


module.exports = (async () => {
    const {
        resolver: { sourceExts, assetExts },
    } = await getDefaultConfig();
    return {
        projectRoot: path.resolve(__dirname, './'),
        transformer: {
            getTransformOptions: async () => ({
                transform: {
                    experimentalImportSupport: false,
                    inlineRequires: false,
                },
            }),
            babelTransformerPath: require.resolve('./transformer.js'), // if you have other transformers that you have to add
        },
        resolver: {
            assetExts: assetExts.filter(ext => ext !== 'svg'),
            sourceExts: [...sourceExts, 'jsx', 'svg'], // you can add more here.
        },
    };
})();

Create a new file called transformer.js (or whatever for that matter but make sure you include it in the metro.config.js file against the babelTransformerPath key, as shown in the metro.config.js sample file above), and put the following code in the transformer.js file.

创建一个名为transformer.js的新文件(或其他相关内容,但请确保将其针对babelTransformerPath密钥包含在metro.config.js文件中,如上面的metro.config.js示例文件所示),然后将下面的代码在transformer.js文件中。

var upstreamTransformer = require("metro-react-native-babel-transformer");
var svgTransformer = require("react-native-svg-transformer")


module.exports.transform = function ({ src, filename, options }) {
    if (filename.endsWith(".svg")) {
        return svgTransformer.transform({ src, filename, options })
    } else {
        return upstreamTransformer.transform({ src, filename, options });
    }
};

All the previous code is doing is that it is telling that in case your file type is svg use the svgTransformer else use the babel transformer

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值