React 組件化思想受到越來越多開發者的關注,組件化思想幫助開發者將頁面解耦成一個一個組件,代碼更加模塊化, 更易擴展。而目前流行的后端模板引擎如 ejs, swig, jade, art 共同的問題是:
- 需要學習各類模板引擎定義的語法,如 {{if}}, {{loop}}
- 對組件化支持不夠強,實現復雜,不易用
針對以上痛點,筆者基于 React 造出了 noox 這樣一個工具,專注于后端模板的解析,讓模板解析更加簡單,易用。
使用方法
安裝
1
|
npm install noox |
簡單的 demo
模板代碼
首先創建組件目錄和增加模板文件
1
2
|
mkdir components && cd components vi Head.jsx |
Head.jsx 內容如下:
1
2
3
4
5
|
< head > < title >{title}</ title > < meta name = "description" content={props.description} /> < link rel = "stylesheet" href = "./css/style.css" rel = "external nofollow" rel = "external nofollow" /> </ head > |
Node.js Code
1
2
3
|
const noox = require( 'noox' ); const nx = new noox(path.resolve(__dirname, './components' ), {title: 'noox' }); let output = nx.render( 'Head' , {description: 'hello, noox.' }) |
輸出
1
2
3
4
5
|
< head > < title >noox</ title > < meta name = "description" content = "hello, noox." /> < link rel = "stylesheet" href = "./css/style.css" rel = "external nofollow" rel = "external nofollow" /> </ head > |
原理
Noox 在 React 的 Jsx 的基礎上,簡化了組件引用和創建,假設創建一個目錄結構如下:
1
2
3
4
|
components/ Header.jsx Body.jsx Layout.jsx |
運行如下 nodejs 的代碼:
1
|
nx = new noox(path.resolve(__dirname, './components' )) |
將會創建三個組件:
- Header
- Body
- Layout
然后通過 nx.render 渲染
1
|
nx.render( 'Body' , props) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://juejin.im/post/5a56073af265da3e4d72994f