从Reaction组件创建纯Web组件 [英] creating pure web component from react components

查看:18
本文介绍了从Reaction组件创建纯Web组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Reaction组件构建Web组件,一切正常,但有两个问题我正在尝试解决:

  1. 有没有办法将此类Web组件转换为纯Web组件(使用webpack、Transspile或其他方式),以便不捆绑Reaction和其他依赖项?
  2. 有没有办法只包含所需的依赖部分,或者只包含ALL/NONE,必须使用webpack的外部设置才能使用宿主的版本?

谢谢

推荐答案

对于第一个问题,没有将Reaction组件转换为Web组件的直接方法。您必须将其包装到Web组件类

export function MyReactComponent() {
  return (
    <div>
      Hello world
    </div>
  );
}


class MyWebComponent extends HTMLElement {
  
  constructor() {
    super();
    // Do something more
  }

  connectedCallback() {
    
    // Create a ShadowDOM
    const root = this.attachShadow({ mode: 'open' });

    // Create a mount element
    const mountPoint = document.createElement('div');
    
    root.appendChild(mountPoint);

    // You can directly use shadow root as a mount point
    ReactDOM.render(<MyReactComponent />, mountPoint);
  }
}

customElements.define('my-web-component', MyWebComponent);

当然,您可以将其泛化并创建一个可重用的函数:

function register(MyReactComponent, name) {
  const WebComponent = class extends HTMLElement {
    constructor() {
      super();
      // Do something more
    }
  
    connectedCallback() {
      
      // Create a ShadowDOM
      const root = this.attachShadow({ mode: 'open' });
  
      // Create a mount element
      const mountPoint = document.createElement('div');
      
      root.appendChild(mountPoint);
  
      // You can directly use shadow root as a mount point
      ReactDOM.render(<MyReactComponent />, mountPoint);
    }
  }
  
  customElements.define(name, MyWebComponent);
}

register(MyReactComponent, 'my-web-component');
现在可以在要公开为Web组件的所有组件中重复使用相同的注册函数。此外,如果您的组件接受应该传递的属性,则该函数可以更改为接受第三个参数作为字符串数组,其中每个值都将使用Object.define注册为该组件的setter。每次调用setter时,只需再次调用ReactDOM.render即可。

现在,对于第二个问题,您尝试执行的操作有多个方案。

  • 如果您正在捆绑应用程序,并使用CDN加载Reaction或其他依赖项,那么webpackexternals是一种选择。在这里,您将教webpack如何从APP将运行的全局环境中替换importrequire
  • 如果要将捆绑到NPM注册表以供其他人在其应用程序中使用,则必须使用library target configuration生成您的项目。阅读有关authoring libraries here的更多信息。
库的捆绑稍微复杂一些,因为您必须决定您的输出格式是什么(Common.js、ES模块或UMD或全局或多种格式)。理想的格式是ES模块,如果你是浏览器捆绑,因为它允许更好的树摇动。Webpack之前不支持模块格式,最近开始支持。总的来说,对于应用程序我推荐webpack,对于库我推荐Rollup.js

这篇关于从Reaction组件创建纯Web组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆