epress proxy+ nodeesi 实现简单微前端

实际上我以前也写过类似的(ssi+client esi 的)以下是一个服务器端的esi 参考玩法(内容来自youtube)

参考图

环境准备

  • http proxy 部分代码
const app = require("express")()
const proxy = require("express-http-proxy")
const ESI = require('nodesi');
const esi = new ESI({
});
app.use('/', proxy('http://localhost:8000', {
    userResDecorator: function (proxyRes, proxyResData) {
        console.log( proxyRes.headers["content-type"])
        return proxyRes.headers["content-type"] === "text/html" || proxyRes.headers["content-type"] === "text/html; charset=utf-8" ?
            esi.process(proxyResData.toString()): proxyResData
    }
}));
 
app.listen(3000)
  • origin 部分
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>demo app</title>
</head>
<body>
    demo page
    <esi:include src="http://localhost:9090/app.html"></esi:include>
</body>
</html>
  • esi 部分
<div class="demoapp">rong demo</div>
  • 项目结构

启动&&效果

  • 启动

    使用独立的终端

cd proxy 
node app.js
cd esi 
live-server --port=9090
cd server
live-server --port=8000
  • 效果

说明

以上是一种基于服务器端渲染的实现,而且是基于代码处理的,实际上我们可以基于现有的esi 中间件(esigate,varnish,nginx 可以方便的解决类似问题)
而且基于组件渲染模式也是一种很不错的微前端实践,业界开源类似的也不少

参考资料

https://www.npmjs.com/package/express-http-proxy
https://github.com/taf2/nginx-esi
http://www.squid-cache.org/Doc/config/esi_parser/
https://varnish-cache.org/docs/6.0/users-guide/esi.html
https://www.npmjs.com/package/nodesi
https://www.youtube.com/watch?v=4PoNBZl4t0Y
http://www.esigate.org/

原文地址:https://www.cnblogs.com/rongfengliang/p/15759331.html