Javascript 渲染并将Preact封装到iframe中

Javascript 渲染并将Preact封装到iframe中,javascript,reactjs,iframe,preact,Javascript,Reactjs,Iframe,Preact,我正在尝试创建一个包含Preact的iframe,它可以在不同的框架中实现。iframe能够通过事件与父窗口通信。我认为,该软件包需要由npm导入。ESM也是一种替代方案,但我不明白在开发过程中如何做到这一点。我曾尝试使用自定义元素,但它没有封装javascript,并且在呈现Preact-inside-React时会导致挂钩错误 我认为以下步骤是可能的: 1.创建我的趣味应用程序。使用微绑定导出es模块 import { h, render } from 'preact' import App

我正在尝试创建一个包含Preact的iframe,它可以在不同的框架中实现。iframe能够通过事件与父窗口通信。我认为,该软件包需要由npm导入。ESM也是一种替代方案,但我不明白在开发过程中如何做到这一点。我曾尝试使用自定义元素,但它没有封装javascript,并且在呈现Preact-inside-React时会导致挂钩错误

我认为以下步骤是可能的:
1.创建我的趣味应用程序。使用微绑定导出es模块

import { h, render } from 'preact'
import App from './containers/app'
import { EventBus } from './utilities/bus'

let container
if (typeof window !== 'undefined') {
  container = document.querySelector('.container')
  window.parent.EventBus = new EventBus()
}
render(h(App), document.querySelector('.container'))

export const start = (rootElement, target) => {
  render(h(App), document.querySelector('.container'))
  // render(h(App), rootElement, target)
  if (typeof window !== 'undefined') {
    window.parent.EventBus = new EventBus()
  }
}
二,。Nextjs导入我的趣味应用程序

import React, { useEffect, useRef } from 'react'
// import 'my-fun-app'

const getBlobURL = (code, type) => {
  const blob = new Blob([code], { type })
  return URL.createObjectURL(blob)
}

const MyFunApp = () => {
  const refContainer = useRef(null)

  useEffect(() => {
    let container = document.createElement('div')
    container.id = 'container'
    refContainer.current.contentDocument.body.appendChild(container)
    let moduleScript = document.createElement('script')
    moduleScript.type = 'module'
    const jsURL = getBlobURL(require('my-fun-app', 'text/javascript')
    moduleScript.src = jsURL
    refContainer.current.contentDocument.head.appendChild(moduleScript)
  }, [])

  return (
    <iframe
      ref={refContainer}
      id="my-iframe"
    ></iframe>
  )
}
import React,{useffect,useRef}来自“React”
//导入“我的乐趣应用程序”
const getBlobURL=(代码,类型)=>{
const blob=新blob([code],{type})
返回URL.createObjectURL(blob)
}
const MyFunApp=()=>{
const refContainer=useRef(null)
useffect(()=>{
让容器=document.createElement('div')
container.id='container'
refContainer.current.contentDocument.body.appendChild(容器)
让moduleScript=document.createElement('script')
moduleScript.type='module'
const jsURL=getBlobURL(require('my-fun-app','text/javascript'))
moduleScript.src=jsURL
refContainer.current.contentDocument.head.appendChild(moduleScript)
}, [])
返回(
)
}
尝试使用

render(<App />, getQuerySelector('#my-iframe').contentWindow.document.body)
render(,getQuerySelector('#我的iframe').contentWindow.document.body)
这会将应用程序呈现到iframe中,但它不会封装它。例如,如果将react hook表单导入到我的fun应用程序中,就会出现某种循环依赖,导致hooks错误

我慢慢地想到这是不可能的,但几乎一切都有可能。希望你能提供一些指导