如何在其他网站上嵌入 React 组件?

Posted

技术标签:

【中文标题】如何在其他网站上嵌入 React 组件?【英文标题】:How to embed React component on other sites? 【发布时间】:2019-12-18 01:24:05 【问题描述】:

我已经创建了 React 应用程序,我需要为其他网站生成嵌入代码。这是一个大型应用程序,我只想将一个组件作为其他域的小部件。我读过Writing embeddable javascript plugin with React & Webpack 和How to embed react component on other domains?。我设置了我的 webpack,但仍然无法在另一个域上呈现小部件。

这个小部件应该:

    可以通过<script>标签获得,而不是iframe 只显示应用的一部分(路径/referral),而不是所有应用

小部件是一个按钮和弹出窗口,通过单击按钮显示。

这是我在client 文件夹中的webpack.config.js

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>

另外,我尝试使用Referral.jswebpack.config.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 应用中的一个组件(不是所有应用)嵌入其他网站。

【问题讨论】:

【参考方案1】:

假设你正确配置你的 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> 

【讨论】:

托尼,感谢您的回复!以及如何为另一个没有 React 的网站添加这个组件的代码? 您需要将 react 与您的代码捆绑在一起,以便它可以在另一个网站上运行 :) 如果我的回答解决了您的问题,请务必投票并接受我的回答。谢谢你 您可以查看我的代码here 基本上您需要有一个入口点,其中包含在网站中运行组件所需的任何内容 this 可能对你有帮助

以上是关于如何在其他网站上嵌入 React 组件?的主要内容,如果未能解决你的问题,请参考以下文章