Skip to content Skip to sidebar Skip to footer

Load React Js Component From External Script In "run Time"

I'm using React JS + webpack. General case that I need to resolve is to dynamically load React components that were not bundled with main application. Kind of pluggable components

Solution 1:

With webpack 5 you can now do this via module federation.

The basic idea is that you "expose" exports from one project to be used in another:

App 1 (uses Button from app2)

<!-- public/index.html --><html><head><!-- remote reference to app 2 --><scriptsrc="http://localhost:3002/remoteEntry.js"></script></head><body><divid="root"></div></body></html>
//app.tsimport * asReactfrom"react";

constRemoteButton = React.lazy(() =>import("app2/Button"));

constApp = () => (
  <div><h1>Typescript</h1><h2>App 1</h2><React.Suspensefallback="Loading Button"><RemoteButton /></React.Suspense></div>
);

exportdefaultApp;

//... webpack.config.jsplugins: [
    newModuleFederationPlugin({
      name: "app1",
      library: { type: "var", name: "app1" },
      remotes: {
        app2: "app2",
      },
      shared: ["react", "react-dom"],
    }),
    newHtmlWebpackPlugin({
      template: "./public/index.html",
    }),
  ]

App 2 (exposes Button)

// src/Button.tsimport * asReactfrom"react";

constButton = () => <button>App 2 Button</button>;

exportdefaultButton;

//... webpack.config.jsplugins: [
    newModuleFederationPlugin({
      name: "app2",
      library: { type: "var", name: "app2" },
      filename: "remoteEntry.js",
      exposes: {
        Button: "./src/Button",
      },
      shared: ["react", "react-dom"],
    })
  ]

Here is a repo containing various examples.

Solution 2:

It sounds like you are asking how to externalize React. If so, you can list libraries as "externals" in your webpack.config.js file:

webpackConfig.externals = {
  "react": "React",
  "react-dom": "ReactDOM",
  ...
}

Post a Comment for "Load React Js Component From External Script In "run Time""