javascript - 如何将 ReactJS 应用程序导出为要在其他应用程序中使用的包?
问题描述
我正在使用webpack和babel来构建我的应用程序,并且应用程序在 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 文件,以便可以在另一个应用程序中使用,就像在给出链接的答案中使用它一样。
解决方案
就像他在另一个答案中所说
<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'));
推荐阅读
- graphql - GraphQL Schema 和 Resolvers 组织返回 null
- r - 如果在 R 中使用超过 1 个组,na.rm 函数将不起作用
- java - 如何连续读取 Firebase (Android) 中的值变化?
- python - 在 Python 中更快地计算矩阵的非零项
- android - 应用程序中的 JNI 检测到错误 - JNI CallVoidMethodV 调用挂起 - 没有此类方法错误 - 使用 Proguard 时
- python - Python集成大数组系数
- css - 在具有负边距的 div 下方发出移动图像
- java - 仅在字符彼此相邻时计算字符
- reactjs - ReactJS 外部库
- python - 删除字典中的类似条目