同構 javascript 應用開發的最佳實踐(3)
上一次我們服務端已經啟動了,而且主要是構建流程已經初步搭建出來了。
所謂同構可以簡單理解為服務端和客戶端共享程式碼,雖然前端和後端我們為了同構使用都是 javascript 進行編寫。但是兩端環境不同,window(瀏覽器)和 precess(伺服器端)。
現在面臨一個問題,既然是程式碼公用,那我們是先寫服務端還是先開發客戶端。可能有人會說同時,那就沒有必要了。因為另一端可以複用和參考已經開發好一端的程式碼。
個人推薦從服務端進行開發,因為服務端開發模式更加固定。
建立模板
模板是現代 web 開發少不了也是繞不開的內容,個人用過很多服務端和客戶端模板,前端為用過 handlebars,最近嘗試過???先留個伏筆。服務端用過 pug 等等。現在我們用 Mozilla 提供的 nunjucks 。這個模板還沒有用過,不得不感嘆現在前端技術更新太快。同樣一個需求會有很多選擇是好事也是壞事,讓我們中話費時間在選擇上。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <p>{{title}} {{author}}</p> </body> </html>
試了試 nunjucks 的 render 方法重視報錯找不到模板檔案,renderString 方法還好用,還得吐槽一下,部分 js 的庫向下相容不好,過一段時間升一下級,就是各種問題暴露出來,學習一下 nunjucks, 算了還是先往下進行,自己讀取檔案然後用renderString方法先替一下,實在不行在研究。
import nunjucks from 'nunjucks'; import Path from 'path'; import fs from 'fs';
fs.readFile(Path.join(__dirname,'/index.html'), {encoding:"utf-8"},(err,file)=>{ if(err){ return "hell world"; } reply(nunjucks.renderString(file, { title: 'basic angular',author:'zidea' })); })
我們把上面程式碼抽取作為方法 render 來使用
function render(path,request,reply,context){ fs.readFile(Path.join(__dirname,path), {encoding:"utf-8"},(err,file)=>{ if(err){ return "hell world"; } reply(nunjucks.renderString(file,context)); }) }
這個 getTutInfo 函式用於將解析 request 物件引數/hello/title/author/ 中將 title 和 author 資訊解析出來生成一個物件用於替換模板中的佔位符
function getTutInfo(request){ console.log(request); let tutInfo = { title: 'basic angular', author:'tina' } let title = request.params.title; let author = request.params.author; return { title:title?title:'default title', author:author?author:'default author' } }
修改路由讓 URL 包含變數用於我們獲取使用。
server.route({ method:'GET', path:'/hello/{title}/{author}', handler:function(request,reply){ render('/index.html',request,reply,getTutInfo(request)); } });