工具:
umijs:react前端應用框架,
koa:基于 Node.js 平臺的web 開發框架,
介紹:
本文主要是簡單介紹,利用umi開發前端頁面,打包成服務端渲染工程包,由Koa實作服務端渲染處理,
程序:
前端部分:
1.正常構建umi工程包,開發web應用,
2.開始ssr配置,
1 export default defineConfig({ 2 ...others, 3 ssr: {}, // 開啟ssr 4 base: '/base/', // root 5 publicPath: '/base/', // root 6 });
3.build命令打包后,會在工程目錄下dist包中產生umi.server.js檔案,該檔案作為服務端渲染的入口,
服務端部分:
1.構建Koa工程,
2.監聽埠,處理請求,代碼源于umi官方示例,
1 const Koa = require("koa"); 2 const compress = require("koa-compress"); 3 const mount = require("koa-mount"); 4 const { join, extname } = require("path"); 5 const { staticPath } = require("./conf/webConf"); 6 const root = join(__dirname, staticPath); 7 8 const app = new Koa(); 9 app.use( 10 compress({ 11 threshold: 2048, 12 gzip: { 13 flush: require("zlib").constants.Z_SYNC_FLUSH, 14 }, 15 deflate: { 16 flush: require("zlib").constants.Z_SYNC_FLUSH, 17 }, 18 br: false, // 禁用br解決https gzip不生效加載緩慢問題 19 }) 20 ); 21 22 let render; 23 app.use(async (ctx, next) => { 24 const ext = extname(ctx.request.path); 25 // 符合要求的路由才進行服務端渲染,否則走靜態檔案邏輯 26 if (!ext) { 27 if (!render) { 28 render = require(`${staticPath}/umi.server`); // 上文中生產的umi.server.js 入口檔案的位置 29 } 30 // 這里默認是字串渲染 31 ctx.type = "text/html"; 32 ctx.status = 200; 33 const { html, error } = await render({ 34 path: ctx.request.url, 35 }); 36 if (error) { 37 console.log("----------------服務端報錯-------------------", error); 38 ctx.throw(500, error); 39 } 40 ctx.body = html; 41 } else { 42 await next(); 43 } 44 }); 45 46 app.use(mount("/base", require("koa-static")(root))); // 靜態資源位置 注意此處,要與訪問的url相匹配,比如現在配置的,
就是以/base開頭的靜態資源重定向到 root指代到目錄 47 48 app.listen(7001); // 服務監聽埠 49 module.exports = app.callback();
結束:
訪問localhost:7001埠,即可訪問由服務端渲染的頁面了,
本文來自博客園,作者:axelccc,轉載請注明原文鏈接:https://www.cnblogs.com/axelccc/p/15991984.html
歡迎訪問 www.apark.site
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/444422.html
標籤:其他
上一篇:egg-jwt的使用
下一篇:淺淺的聊一下 WebSocket
