簡體   English   中英

在“運行時”從外部腳本加載 React JS 組件

[英]Load React JS component from external script in “run time”

我正在使用 React JS + webpack。 我需要解決的一般情況是動態加載未與主應用程序捆綁的 React 組件。 一種可以獨立於主應用程序開發,然后由應用程序動態加載的可插拔組件,無需重建整個應用程序。

具體案例如下。

我有兩個完全分離的模塊(即使用不同的 package.json 和 webpack.config.js 構建):

  • 主應用MainApp
  • 一些Component

我需要實現以下行為:

  1. 加載和初始化MainApp頁面。
  2. MainApp動態查找包含Component的 .js 文件的 url(例如,通過向 Web 服務器發出 GET 請求)。
  3. MainApp使用Component加載 .js 文件並將其作為<script>包含到頁面中
  4. MainApp在渲染時使用加載的Component

在 react js + webpack 中可以使用這種用例嗎?

使用 webpack 5,您現在可以通過module federation來做到這一點。

基本思想是您“公開”一個項目的導出以在另一個項目中使用:

App 1(使用 app2 中的 Button)

<!-- public/index.html -->
<html>

<head>
  <!-- remote reference to app 2 -->
  <script src="http://localhost:3002/remoteEntry.js"></script>
</head>

<body>
  <div id="root"></div>
</body>

</html>

//app.ts
import * as React from "react";

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

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

export default App;

//... webpack.config.js
plugins: [
    new ModuleFederationPlugin({
      name: "app1",
      library: { type: "var", name: "app1" },
      remotes: {
        app2: "app2",
      },
      shared: ["react", "react-dom"],
    }),
    new HtmlWebpackPlugin({
      template: "./public/index.html",
    }),
  ]

App 2(暴露按鈕)

// src/Button.ts
import * as React from "react";

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

export default Button;

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

這是一個包含各種示例的存儲庫

聽起來您是在問如何將 React 外化。 如果是這樣,您可以在webpack.config.js文件webpack.config.js庫列為“外部”:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM