我已经创建了 React 应用程序,我需要生成其他网站的嵌入代码。这是一个大型应用程序,我只想将一个组件作为其他域的小部件。我已阅读使用 React 和 Webpack 编写可嵌入的 Javascript 插件和如何在其他域上嵌入 React 组件?。我设置了 webpack,但仍然无法在另一个域上渲染小部件。
这个小部件应该:
<script>
标签使用,而不是 iframe/referral
),但不显示全部应用程序小部件是一个按钮和弹出窗口,通过单击按钮显示。
这是我的
webpack.config.js
在 client
文件夹中:
const path = require('path');
const bundleOutputDir = './referral';
const env = require('yargs').argv.env;
module.exports = env => {
const isDevBuild = !(env && env.prod);
if (env === 'build') {
mode = 'production';
} else {
mode = 'development';
}
return [
{
mode: mode,
entry: './src/components/early-referrals/Referral.js',
output: {
filename: 'widget.js',
path: path.resolve(bundleOutputDir),
library: 'Referral',
libraryTarget: 'umd',
umdNamedDefine: true
},
devServer: {
contentBase: bundleOutputDir
},
module: {
rules: [
{ test: /\.html$/i, use: 'html-loader' },
{
test: /\.css$/i,
use: [
'style-loader',
'css-loader' + (isDevBuild ? '' : '?minimize')
]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: 'file-loader'
}
]
},
{
test: /(\.jsx|\.js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: [
[
'@babel/env',
{
targets: {
browsers: ['ie 6', 'safari 7']
}
}
]
]
}
}
}
]
}
}
];
};
这是组件
RegisterReferral.js
,它是 webpack 中的入口点:
import PopupRef from '../popup/PopupRef';
const RegisterReferral = ({
...
}) => {
const [...] = useState();
useEffect(() => {
...
}, []);
return (
<div>
// some styles for button that displays popup
<PopupRef />
</div>
);
};
const mapStateToProps = state => ({
...
});
export default connect(
mapStateToProps,
{ ... }
)(RegisterReferral);
PopupRef.js
是一个带有弹出窗口的组件,应该在按钮内显示在其他网站上。
在
App.js
中,我有这个组件的路径,我想将其创建为可嵌入组件:
<Route exact path="/referral" component={RegisterReferral} />
这是我将代码粘贴到另一个域的一种方法:
// the URL in script is an URL of bundle file from webpack
<html>
<head>
<script src="http://example.com/client/referral/widget.js" type="text/javascript"></script>
</head>
<body>
<p>Another website</p>
<div id='app'></div>
</body>
</html>
另外,我尝试用
webpack.config.js
在 Referral.js
中做入口点。这是这个组件:
// Referral.js
import React from 'react';
import { render } from 'react-dom';
import App from './RegisterReferral.js';
render(<App />, document.getElementById('app'));
// At this case, webpack.config.js has 2 changes:
entry: './src/components/early-referrals/Referral.js',
output: {
...
library: 'Referral',
},
没有任何效果。我的组件不显示在其他网站上。
请帮助我找出问题所在以及如何从其他网站上的 React 应用程序嵌入一个组件(不是所有应用程序)。
假设你正确配置了你的 webpack 来捆绑 React js 代码
这就是我在任何我想要的页面中渲染组件的方式
例如我有这个组件
import React, {Component} from "react";
import {render} from "react-dom";
class LoginForm extends Component { }
render(<LoginForm/>, document.getElementById("loginForm")); // use render method
编辑:
刚刚看到你的代码,我认为你还需要更改index.html中的id
<div id="root"></div>
到
<div id="referral"></div>