我正在尝试使用Web组件方法使用微前端创建演示应用程序。我需要做什么,以便可以从一个微前端到缝合层使用已定义的自定义元素?
我已经采用了IFrame路由,并使用了都可以使用的单spa,但是这次我试图使用Web组件,但没有运气。
我还尝试将微前端添加到Docker容器,但这没有带来任何变化。
我在微前端中定义我的自定义元素,如下所示:
class CommentSection extends HTMLElement {
connectedCallback() {
ReactDOM.render(<App />, this.attachShadow({mode: 'open'}));
}
}
window.customElements.define('comment-section', CommentSection);
我在微前端
index.html
中使用它:<comment-section></comment-section>
到目前为止,一切正常。当我试图从拼接层使用它时,我的问题就来了。
在React应用程序中,我创建了一个
server.js
文件来传递内容:server.get('/', (req, res) => {
const htmlPath = path.resolve(__dirname, 'build', 'index.html');
fs.readFile(htmlPath, 'utf8', (err, html) => {
const rootElem = '<comment-section>';
const renderedApp = renderToString(React.createElement(App, null));
res.send(html.replace(rootElem, rootElem + renderedApp));
});
});
server.use(express.static('build'));
从拼接层创建面向微型前端的代理:
app.use(express.static(__dirname + '/public'));
const createProxy = (path, target) => {
app.use(path, proxy({ target, changeOrigin: true, pathRewrite: {[`^${path}`]: ''} }));
}
createProxy('/react', 'http://localhost:3000');
app.get('/', (req, res) => res.render('index'));
并在拼接
index.html
中将其导入,如下所示:<head>
<link href="/react" rel="import" async/>
</head>
<body>
<comment-section></comment-section>
</body>
我期望Web组件能够像我独立运行微前端时那样在拼接层中呈现react组件,但是实际结果是所有代码都在
link
html import标记下,并且Web组件标签下未呈现任何内容。Web组件微前端
Web组件拼接层
最佳答案
您的示例看起来过于复杂。 Web组件由两部分组成:自定义元素和定义它的脚本。
因此,要呈现Web组件,您只需要将脚本添加到目标html中,就您而言,<script src="/static/js/xxx.js"></script>
就足够了。无需Docker,Proxy等。
换句话说:无论在何处放置Web组件,都应使用与“微型前端” index.html文件中完全相同的方式使用。
关于<link ref="import">
:不推荐使用HTML导入(Chrome:https://www.chromestatus.com/feature/5144752345317376 Firefox:https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports)
关于javascript - 如何从缝合层中的微前端重用已定义的Web组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56076667/