Dynamically loading React components

I am thinking of creating a web application where people can install plugins. I would like plugins to be able to determine the React components that will be displayed on the page, without recompiling the main JavaScript package after installing the plugin.

So here is the approach I'm thinking of:

  • Combine core JavaScript with React as an external library using a web package.
  • Invite plugin authors to compile their components with React as an external library.

Thus, I run only one instance of React. I could do the same with some other commonly used libraries.

The problem is how to dynamically load these plugin components from the server. Suppose I have the following component:

class PluginRenderer extends React.Component{
  componentWillMount() {
    getPluginComponent('/plugins/${this.props.plugin}/component.js').then((com) => {
      this.setState({pluginComponent: com});
    })
  }

  render() {
    var Plugin = this.state.pluginComponent;
    return Plugin ? <Plugin {...this.props} /> : "Loading..."
  }
}

getPluginComponent?

+8
2

, , . :

  • Webpack, , CLI, .

  • Webpack externals , : React, Redux .. , , window . , , , 1000 .

  • external, . PluginService.register(), . : , : ", , (, UI)" .

  • / PluginCache, (pluginId → , , fn, class, ). - , . <Loading /> <Error />, ..

  • PluginService/Manager ( ?), script . , register, 3, , 4 .

  • , , .

, ( , / " ", ).

<Provider store={ theCoreStore } > , Redux - , ... , .:)

, , -!

+7

. :

import(/* webpackIgnore: true */'https://any.url/file.js')
  .then((plugin) => {
    plugin.main({ /* stuff from app plugins need... */ });
  });

...

const main = (args) => console.log('The plugin was started.');
export { main };
export default main;

. .

0

Source: https://habr.com/ru/post/1680195/


All Articles