首页 > 解决方案 > 如何实现 RAM bundle 和 Inline Requires react native

问题描述

我正在使用本机反应来构建项目,并且我面临启动时间长的问题,我尝试遵循https://reactnative.dev/docs/ram-bundles-inline-requires,但是关于调查并不清楚加载的模块,以及如何只为第一个屏幕放置必要的模块。我也找不到 index.(ios​​|android).js 文件(是 index.android.bundle)。如果你能告诉我如何只提取必要的模块并推荐有关实现它的文档或示例?

标签: react-native

解决方案


With considering the official documents, pay attention to this example:

You have a Main screen (view) in your app like HomeScreen

In your HomeScreen, there are more and more components and logic in this page but assume we have a SettingsModal.

usually, modals will open when you touch a button.

Without inline require

you have to import your modal component to your HomeScreen at the top level of your module

with inline require

you will import your modal component to your HomeScreen when it needs to show!

Let's do this with code:

HomeScreen without inline require

import React, {useState} from 'react'
import {View, Text, Pressable} from 'react-native'
import SettingsModal from 'components/modal'

function HomeScreen() {
    const [showModal, setShowModal] = useState(false)

    const handleShowModal = () => setShowModal(prevState => !prevState)
   
    return (
       <View>
          <Text> Home Screen </Text>

          <Pressable onPress={handleShowModal}>
              <Text> show settings </Text>             
          </Pressable >

          {
            showModal 
                ?  <SettingsModal />
                :  null
          }
       </View>
    )
}

In the above example, we import SettingsModal in our HomeScreen top level with React and View and Text...

HomeScreen with inline require

import React, {useState} from 'react'
import {View, Text, Pressable} from 'react-native'

let SettingsModal = null;

function HomeScreen() {
    const [showModal, setShowModal] = useState(false)

    const handleShowModal = prevState => {
         if (SettingsModal == null) {
             SettingsModal = require('components/modal').SettingsModal
         }
         
         setShowModal(prevState => !prevState)
    }
   
    return (
       <View>
          <Text> Home Screen </Text>

          <Pressable onPress={handleShowModal}>
              <Text> show settings </Text>             
          </Pressable >

          {
            showModal 
                ?  <SettingsModal />
                :  null
          }
       </View>
    )
}

In the above example, we check if SettingsModal has not been imported yet, then we will import this component to our HomeScreen file (after user touch the show settings button)


推荐阅读