简体   繁体   English

如何从存储在变量中的路径延迟加载 React Native 模块

[英]How to Lazy-Load a React Native module from a path stored in a variable

I've been trying to load a React Native component dynamically, but to no success.我一直在尝试动态加载React Native组件,但没有成功。 It seems like React Native doesn't like it at all when you try passing it a module path stored in a variable:当您尝试将存储在变量中的模块路径传递给它时, React Native似乎根本不喜欢它:

This works very well - React.lazy :这非常有效 - React.lazy

const OtherComponent = React.lazy(() => import('./path/to/my/module'));

This also works like a charm Full dynamic import: - Full dynamic import: @loadable/component这也像一个魅力完全动态导入:- 完全动态导入:@loadable/component

(npm @loadable/component) (npm @loadable/组件)

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import('./path/to/my/module'))

but try changing any to this:但尝试将任何更改为此:

var myModulePath = './path/to/my/module';  

const AsyncPage = loadable(props => import(myModulePath))

or this:或这个:

const OtherComponent = React.lazy(() => import(myModulePath));

and all goes crazy!一切都变得疯狂了!

How can I go about loading a module dynamically, say at runtime , or just have the path briefly held in a variable, instead of passing it as a string literal我 go 如何动态加载模块,比如在运行时,或者只是将路径短暂保存在变量中,而不是将其作为string literal传递

From the documentation ( Full dynamic import: @loadable/component ),从文档( 完全动态导入:@loadable/component ),

import loadable from '@loadable/component'
const AsyncPage = loadable(props => import(`./${props.page}`))

a dynamically generated path should work, but my React Native attempts don't.动态生成的路径应该有效,但我的React Native尝试无效。

Are there any ideas out there?那里有什么想法吗?

Thank you all in advance.谢谢大家。

You can do it using https://github.com/microsoft/react-native-code-push您可以使用https://github.com/microsoft/react-native-code-push来完成

About lazy loading, it is not needed if you use the Hermes JS engine.关于延迟加载,如果你使用Hermes JS引擎,则不需要。 Otherwise, you can use RAM bundler: https://reactnative.dev/docs/ram-bundles-inline-requires否则,您可以使用 RAM 捆绑器: https://reactnative.dev/docs/ram-bundles-inline-requires

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

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