在“运行时”

时间:2016-11-15 16:32:46

标签: javascript node.js reactjs webpack

我正在使用React JS + webpack。 我需要解决的一般情况是动态加载未与主应用程序捆绑在一起的React组件。一种可插拔组件,可以独立于主应用程序开发,然后动态加载应用程序,而无需重建整个应用程序。

具体案例如下。

我有两个完全分离的模块(即使用不同的package.json和webpack.config.js构建):

  • MainApp
  • 部分Component

我需要实现以下行为:

  1. 加载并初始化MainApp的网页。
  2. MainApp动态查找包含Component的.js文件的网址(例如,向网络服务器发出GET请求)。
  3. MainApp使用Component加载.js文件并将其包含在页面<script>
  4. MainApp在渲染时使用加载的Component
  5. 反应js + webpack中是否可以使用这种用例?

2 个答案:

答案 0 :(得分:1)

使用webpack 5,您现在可以通过module federation进行此操作。

基本思想是,您“暴露”一个项目中的导出内容以供另一个项目使用:

应用1(使用app2中的按钮)

<!-- 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",
    }),
  ]

应用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"],
    })
  ]

这里是repo containing various examples

答案 1 :(得分:0)

听起来你在问如何外化反应。如果是这样,你可以将图书馆作为&#34; externals&#34;在你的webpack中 - 这是一个例子:https://github.com/flexicious/react-redux-datagrid/blob/master/config/webpack.config.js

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

只是快速说明flexicious-react-datagrid是我们的反应数据网格组件 - [http://reactdatagrid.com]所以除非你使用它,否则你不需要它在你的外部