文章來源:https://www.npmjs.com/package/ftl-server
源代碼可參考:https://github.com/szmtcjm/ftl-server/blob/master/lib/config.js
ftl-server 是一前端開發工具,支持解析freemarker模板,模擬后端接口,反向代理等功能。
特性
- 解析freemarker模板
- 靜態資源服務
- mock請求
- 代理請求
- livereload
- weinre
安裝
1. npm install ftl-server -g
2. 在工程目錄下新建配置文件,比如ftl.config.js,配置文件格式如下:
module.exports = {
public: 'E:\\somedir\\public', //靜態文件目錄
port: '80', //端口號,默認為80
hot: true, //布爾值,是否開啟livereload;開啟后修改css會自動更新頁面的樣式,修改ftl/js/圖片等會自動刷新頁面
watch: [require.resolve('./page.ftl'), 'E:\\ftlServer\page.mock'], //需要監控的額外的配置文件,值為數組
remoteDebug: { //remoteDebug
針對weinre的配置
browser: 'firefox'
},
ftl: { //配置freemarker的解析
base: 'E:\\somedir\\ftl', //配置freemarker模板目錄
dataFiles: ['E:\\somedir\\data.ftl'], //配置ftl模板需要的數據文件,也就是造假數據的文件
global: { //ftl共享的數據文件
},
'ftlfile.ftl': function(req, res) { //key ftlfile.ftl表示要渲染的ftl文件, value表示該渲染該ftl的數據
return {
saleActivityMap: {
"000008": {
activityStatus: 'actived'
}
}
}
}
},
mock: [{ //接口模擬,模擬請求
path: '/request', //請求名
method: 'get', //請求方法
status: '200', //請求狀態
header: { //請求頭
},
response: function(req, res) { //請求的返回內容
return {
a: 1,
B: 2
}
}
}, 'E:\\mock\\mock.js'], //文件格式見下面的源代碼
proxy: [{
path: '/proxy1', //表示需要反向代理的請求path
target: 'http://localhost:3000' //表示代理的目標地址
}
]
}
E:\\mock\\mock.js格式如下:
// /dir/mock.js // 可以export一數組,或者直接一對象 module.exports = [{ path: '/mock', method: 'post', response: function(req, res) { return { result: true } } }]
執行 fs -c ./ftl.config.js -p 1008 或 ftl-server -c ./ftl.config.js -p 1008 或 fs
3. 訪問 http://localhost:1008/,即可直接瀏覽目錄下的ftl頁面。
項目實踐
1. 項目根目錄下新建 ftl.config.js
1.1默認配置文件名為 ftl.config.js,啟動時bash命令執行 fs 或 ftl-server
1.2如果是自定義配置文件名稱,比如 config.js,則每次配置文件改動,或者啟動ftl server時,bash命令需執行 fs -c ./config.js 或 ftl-server -c ./config.js
需要重新設置配置文件的路徑。
2. ftl.config.js 代碼內容
module.exports = { public: '/Users/xx/Projects/bbb/src/main/webapp', port: '10080', hot: true, ftl: { base: '/Users/xx/Projects/bbb/src/main/webapp/WEB-INF/template', }, mock: ['/Users/xx/Projects/bbb/src/main/webapp/WEB-INF/template/fakeData/ajax/cc.js'], proxy: [{ path: '/proxy1', target: 'http://localhost:3000' } ] }
一些不常用的配置項沒加進去,ftl.dataFiles里不能配置ftl文件的目錄,只能配名字,這點不是很方便。
如果頁面需要假數據,直接在頁面上assign假數據就可以了。或者將assign的假數據單獨建個ftl文件,然后在需要假數據的ftl include進去就行。
3. mock數據請求
mock配置頁面需要發的一些請求,數組表示。如下:
/Users/xx/Projects/bbb/src/main/webapp/WEB-INF/template/fakeData/ajax/cc.js
module.exports = [{ path: '/ajax.html', method: 'get', status: 200, response: function(req, res) { return { "code": "200", "msg": "操作成功" } } }]
4.啟動服務
bash命令執行 fs 或 ftl-server
可以使用 fs --help 查看其它的操作。