在“运行时"中从外部脚本加载React JS组件. [英] Load React JS component from external script in "run time"
问题描述
我正在使用React JS + webpack.我需要解决的一般情况是动态加载未与主应用程序捆绑在一起的React组件.一种可插拔的组件,可以与主应用程序独立开发,然后由应用程序动态加载,而无需重建整个应用程序.
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 that can be developed independently from main app and then loaded by application dynamically, without rebuilding whole app.
特殊情况如下.
我有两个完全分开的模块(即使用不同的package.json和webpack.config.js构建):
I have two completely separated modules (i.e. built using different package.json and webpack.config.js):
-
MainApp
- 一些
Component
我需要实现以下行为:
- 已加载并初始化了
MainApp
的页面. -
MainApp
动态查找包含Component
的.js文件的网址(例如,通过向Web服务器发出GET请求). -
MainApp
使用Component
加载.js文件,并将其作为< script>
包含到页面中 -
MainApp
在渲染时使用加载的Component
.
- Page with
MainApp
loaded and initialized. MainApp
dynamicaly lookup for url of .js file that containsComponent
(e.g. by making GET request to web-server).MainApp
loads .js file withComponent
and include it to page as<script>
MainApp
uses loadedComponent
while rendering.
在React js + Webpack中这种用例可行吗?
Is such use-case possible in react js + webpack?
推荐答案
使用Webpack 5,您现在可以通过模块联盟.
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:
应用程序1(使用来自应用程序2的按钮)
<!-- 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"],
})
]
这是一个回购,其中包含各种示例.
这篇关于在“运行时"中从外部脚本加载React JS组件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!