Friday, 28 April 2017

Make React Load Components Dynamically Based on an Extensible Global Registry

I'm trying to build something that's going to be open source, and want to have a "plugin" model where people can extend basic functionality with their own component ("module") types.

But since import statements have to be static, I'm not sure how to accomplish that.

Here's some pseudo code:

parent.js

//import all the modules that have been defined in the registry and its extensions
//So the effect should be:
// import ModuleA from './module_a';
// import ModuleB from './module_b';
// import ModuleC from './module_c';
// import ModuleD from './module_d';

GLOBAL_REGISTRY.forEach((module) => {
    import module.componentName from module.path;
});

class ParentModule extends Component {
    render(){
        //props.moduleType would be something like ModuleC
        const SpecificModule = props.moduleType;
        return <SpecificModule config={this.props.config} />;
    }
}

registry.js

GLOBAL_REGISTRY = [
  {
    componentName: 'ModuleA',
    path: './module_a'
  },
  {
    componentName: 'ModuleB',
    path: './module_b'
  }
]

registry_extended.js

//This may be in a completely different project. The goal is to allow other projects to extend the registry
//So registry.js and parent.js won't know about registry_extended.js
GLOBAL_REGISTRY.push(
  {
    componentName: 'ModuleC',
    path: './module_c'
  },
  {
    componentName: 'ModuleD',
    path: './module_d'
  }
);

So my question boils down to, "how can I make an registry that can be extended by other projects, and then dynamically import and use component files in parent.js based on that registry?"

Thanks in advance!



via Sam

No comments:

Post a Comment