疾速初始化
应用脚手架,对我的项目进行疾速初始化
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
启动我的项目
$ npm run dev
$ open http://localhost:7001
拜访成果如下
逐渐搭建
初始化我的项目
$ mkdir egg-example
$ cd egg-example
$ npm init
$ npm i egg --save
$ npm i egg-bin --save-dev
增加相干的执行脚本
{
"name": "egg-example",
"scripts": {"dev": "egg-bin dev"}
}
编写 Controller
const Controller = require('egg').Controller;
class HomeController extends Controller {async index(){this.ctx.body = 'Hello World';}
}
module.exports = HomeController;
增加路由
module.exports = app => {const {router, controller} = app;
router.get('/', controller.home.index);
}
增加配置文件
exports.keys = '_1595046215730_9281';
此时目录文件构造
拜访成果
此时输出命令
npm run dev
输出地址进行拜访
http://localhost:7001
成果如下
动态资源
这里应用 egg.js 的插件实现对 egg.js 文件进行解决。
启动我的项目,拜访动态资源
http://localhost:7001/public/js/lib.js
而后就能够拜访了。
模板渲染
在本例子中,应用 egg-view-nunjucks 作为插件,进行模板的渲染
装置插件
C:\Users\Administrator\Desktop\untitled2\egg-example>npm i egg-view-nunjucks --save
npm WARN acorn-jsx@5.2.0 requires a peer of acorn@^6.0.0 || ^7.0.0 but none is installed. You must install peer dependencies yo
urself.
npm WARN co-mocha@1.2.2 requires a peer of mocha@>=1.18 <6 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (cu
rrent: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.3 (node_modules\nunjucks\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.3: wanted {"os":"darwin","arch":"any"} (cur
rent: {"os":"win32","arch":"x64"})
+ egg-view-nunjucks@2.2.0
added 1 package from 1 contributor in 11.263s
36 packages are looking for funding
run `npm fund` for details
C:\Users\Administrator\Desktop\untitled2\egg-example>
实现了插件的装置
开启插件
配置如下目录,开启插件
config/plugin.js
配置内容如下
exports.nunjucks = {
enable: true,
package: 'egg-view-nunjucks'
};
批改总的配置文件
exports.keys = "_fduhuhrefguir83238uhfr";
exports.view = {
defaultViewEngine: 'nunjucks',
mapping: {'.tpl': 'nunjucks',},
}
编写模板文件
在 app/view 文件下减少新的模板文件。
<!-- app/view/news/list.tpl -->
<html>
<head>
<title>Hacker News</title>
<link rel="stylesheet" href="/public/css/news.css" />
</head>
<body>
<ul class="news-view view">
{% for item in list %}
<li class="item">
<a href="{{item.url}}">{{item.title}}</a>
</li>
{% endfor %}
</ul>
</body>
</html>
增加控制器和路由
const Controller = require('egg').Controller;
class NewsController extends Controller {
// 同步,设置模板参数列表
async list() {
const dataList = {
list: [{ id: 1, title: 'this is news 1', url: '/news/1'},
{id: 2, title: 'this is news 2', url: '/news/2'}
]
};
// 期待进入 render
await this.ctx.render('news/list.tpl', dataList);
}
}
module.exports = NewsController;
增加路由
module.exports = app => {const { router, controller} = app;
router.get('/', controller.home.index);
router.get('/news', controller.news.list);
};
拜访 http://localhost:7001/news 即可看到页面
编写 service
在 app/service 目录下,增加 service 相干文件。
代码如下
const Service = require('egg').Service;
class NewsService extends Service {async list(page = 1) {
// read config
const {serverUrl, pageSize} = this.config.news;
// use build-in http client to GET hacker-news api
const {data: idList} = await this.ctx.curl(`${serverUrl}/topstories.json`, {
data: {
orderBy: '"$key"',
startAt: `"${pageSize * (page - 1)}"`,
endAt: `"${pageSize * page - 1}"`,
},
dataType: 'json',
});
// parallel GET detail
const newsList = await Promise.all(Object.keys(idList).map(key => {const url = `${serverUrl}/item/${idList[key]}.json`;
return this.ctx.curl(url, { dataType: 'json'});
})
);
return newsList.map(res => res.data);
}
}
module.exports = NewsService;
批改 Controller 增加相干的 service
const Controller = require('egg').Controller;
class NewsController extends Controller {async list() {
const ctx = this.ctx;
const page = ctx.query.page || 1;
const newsList = await ctx.service.news.list(page);
await ctx.render('news/list.tpl', { list: newsList});
}
}
module.exports = NewsController;
此时 ctx.service.news.list 提供相干的数据。
减少配置文件
这时减少相干的配置文件
exports.news = {
pageSize: 5,
serverUrl: 'https://hacker-news.firebaseio.com/v0',
};
在模板里增加自定义函数
装置插件
npm i moment --save
// app/extend/helper.js
const moment = require('moment');
exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();
<!-- app/view/news/list.tpl -->
{{helper.relativeTime(item.time) }}
编写中间件
// app/middleware/robot.js
// options === app.config.robot
module.exports = (options, app) => {return async function robotMiddleware(ctx, next) {const source = ctx.get('user-agent') || '';
const match = options.ua.some(ua => ua.test(source));
if (match) {
ctx.status = 403;
ctx.message = 'Go away, robot.';
} else {await next();
}
}
};
// config/config.default.js
// add middleware robot
exports.middleware = ['robot'];
// robot's configurations
exports.robot = {
ua: [/Baiduspider/i,]
};
最初
对于 egg.js 来说,总体上也是 MVC 三层架构。外加中间件,设置相干的文件。
当前的内容将会再次挨个深刻解说。