通过变量动态导入文件 - react-native

IT技术 reactjs react-native ecmascript-6 metro-bundler
2021-05-14 21:08:54

我有一个包含组件路径的 path.json 文件

// path.json

{
  "main": "./login/index.js",
  "paths": [
    {
      "name": "login",
      "path": "./login/index.js",
      "image": ""
    }
  ]
}

我想在 react native 中动态加载'./login/index.js'文件并渲染这个特定的文件

我目前的实施

const MyComponent = createLazyContainer(() => {
  const componentPath = PathJson.main; // ./login/index.js
  return import(`${componentPath}`); //import error here @ line 7
});

export default MyComponent;

我收到以下错误:

第 7 行的无效调用:import("" + componentPath)

4个回答

人们在线程中告诉您的内容是正确的,但我想添加一种可能的解决方案。所有导入/要求都在编译时解决,而不是在您尝试执行的运行时解决。在您运行应用程序时,如果您尚未导入文件,则无法使用它们。

有一个解决方法,假设您事先知道所有可能用于做工厂之类的文件:

   const possiblePaths = {
     'one': require('path/to/file/1),
    'two': require('path/to/file/2)
}

funtion(type){
    return possiblePaths[type]
}

然后你以某种方式使用它:

render(){
   const MyComponent = function('one')

  return <MyComponent/>
}

这或多或少是伪代码,我不能马上工作,但希望你能明白。您需要存储对您可能需要的每个导入的引用,然后不要使用导入,而是使用在编译时为您创建的引用。

在 React Native 中,所有导入的文件都捆绑在一起,只有那些文件可以动态导入。

比方说,你有三个文件index.jstest_1.js并且test_2.js,如果你有进口只test_1.jsindex.js比原生做出react只会捆绑这两个文件离开test_2.js

因此,即使动态导入在 React Native 中有效,也要回答您的问题,但由于这些文件不是包的一部分,您无法导入它们。

实际上, React Native开发关注点与Web开发不同

正是因为这个原因,在 react-native 项目的生产中延迟加载根本不是那么重要只需导入您想要的任何内容,然后在项目的任何文件中使用它们。所有这些都在生产包中,完全不重要。

所以对于这个问题,我更喜欢有一个帮助文件来收集所有可选择的库并导出它们:

// helper file
export { default as Index } from './Login';
export { default as OtherComponent } from './OtherComponent';

然后当你想使用:

import { Index, OtherComponent } from 'helper';

~~~

render() {
  const MyComponent = someCondition ? Index : OtherComponent;

  return (
    <MyComponent />;
  );
}

解决方案:

const allPaths = {
  path1: require('file path1').default,
  path2: require('file path2').default
};
 render(){
  const MyComponent = allPaths["path1"];

  return <MyComponent/>
 }