javascript - 如何在其他站点嵌入 React 组件?

标签 javascript node.js reactjs webpack ecmascript-6

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

这个小部件应该:

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

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

这是我的 webpack.config.jsclient文件夹:

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> 

关于javascript - 如何在其他站点嵌入 React 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57444674/

相关文章:

javascript - react native : how to render state

javascript - JSFiddle 在本地不起作用

node.js - `mongoose-lean-getters` 无法与 `find` 正常工作,调用 getter 方法两次

javascript - 如何将两个函数传递给 react 中的onClick事件

javascript - render 没有返回任何东西

javascript - 对目录的非法操作,打开

node.js - 如何使用 Node Puppeteer 设置 select 的值

node.js - 多次调用 PassportJS 中间件

javascript - Redux reducer 中的传播运算符

javascript - 动态生成页面上的 jQuery 工具提示