我正在尝试用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导入标记下,而web组件标记下没有呈现任何内容。
web组件微前端
web组件拼接层
发布于 2019-05-15 20:22:42
您的示例看起来过于复杂。Web组件由两部分组成:自定义元素和在其中定义它的脚本。
因此,要呈现Web组件,只需将脚本添加到目标html中,在本例中为<script src="/static/js/xxx.js"></script>
,仅此而已。不需要Docker、代理等。
换句话说:您应该在任何地方使用Web组件,就像在“微前端”index.html文件中一样。
关于火狐:超文本标记语言导入已被弃用(Chrome:https://www.chromestatus.com/feature/5144752345317376 <link ref="import">
:https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports)
https://stackoverflow.com/questions/56076667
复制相似问题