首页 > 解决方案 > 如何将 ReactJS 应用程序导出为要在其他应用程序中使用的包?

问题描述

我正在使用webpackbabel来构建我的应用程序,并且应用程序在 bundle.js 文件中成功构建。

我有包含此代码的 index.jsx 文件

import React from 'react';
import { render } from 'react-dom';
import App from './App';

render(<App />, document.getElementById('app'));

应用程序组件加载了许多其他组件。

我在同一个应用程序中有 index.html 文件。

<html>
  <head>
    <meta charset="utf-8">
    <title>My App</title>
  </head>
  <body>
    <div id="app" />
    <script src="public/bundle.js" type="text/javascript"></script>
  </body>
</html>

我直接在浏览器中打开系统目录中的 index.html 文件,并且应用程序运行良好。

我想要做的是使用 bundle.js 文件并将我的脚本加载到另一个 html/javascript 应用程序中,该应用程序在其中运行相同的应用程序。

我发现这个Writing embeddable Javascript plugin with React & Webpack链接显示了他是如何设法使用它的。

他在哪里使用

export const init = (config) => {
  ReactDOM.render(<MyReactApp config={config} />, someSelector);
}

如何转换我的 index.jsx 文件,以便可以在另一个应用程序中使用,就像在给出链接的答案中使用它一样。

标签: javascriptreactjswebpackbabeljs

解决方案


就像他在另一个答案中所说

<script src="./bundle.js" type="text/javascript"></script>
<script type="text/javascript">
  MyApp.yourExportedFunction();
</script>

但这只是为了使用导出的函数。看起来您想让整个应用程序在其他应用程序的不同 index.html 文件中呈现,因此在其他应用程序的 index.html 中,您需要:

<div id="app"></div>

<script src=".path/to/other/project/bundle.js" type="text/javascript"></script>

然后应用程序将在您的标签内呈现,div#app因为这就是您的库所做的:

render(<App />, document.getElementById('app'));

推荐阅读