本文将从实例的角度,一步步地搭建出一个 Egg.js 应用,让你能快速的入门 Egg.js。

环境准备

  • 操作系统:支持 macOS,Linux,Windows
  • 运行环境:建议选择 LTS 版本,最低要求 8.x。

快速初始化

我们推荐直接使用脚手架,只需几条简单指令,即可快速生成项目:

  1. $ npm i egg-init -g
  2. $ egg-init egg-example --type=simple
  3. $ cd egg-example
  4. $ npm i

启动项目:

  1. $ npm run dev
  2. $ open localhost:7001

逐步搭建

通常你可以通过上一节的方式,使用 egg-init 快速选择适合对应业务模型的脚手架,快速启动 Egg.js 项目的开发。

但为了让大家更好的了解 Egg.js,接下来,我们将跳过脚手架,手动一步步的搭建出一个 Hacker News

注意:实际项目中,我们推荐使用上一节的脚手架直接初始化。

Egg HackerNews Snapshoot

初始化项目

先来初始化下目录结构:

  1. $ mkdir egg-example
  2. $ cd egg-example
  3. $ npm init
  4. $ npm i egg --save
  5. $ npm i egg-bin --save-dev

添加 npm scriptspackage.json

  1. {
  2. "name": "egg-example",
  3. "scripts": {
  4. "dev": "egg-bin dev"
  5. }
  6. }

编写 Controller

如果你熟悉 Web 开发或 MVC,肯定猜到我们第一步需要编写的是 ControllerRouter

  1. // app/controller/home.js
  2. const Controller = require('egg').Controller;
  3. class HomeController extends Controller {
  4. async index() {
  5. this.ctx.body = 'Hello world';
  6. }
  7. }
  8. module.exports = HomeController;

配置路由映射:

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.get('/', controller.home.index);
  5. };

加一个配置文件

  1. // config/config.default.js
  2. exports.keys = <此处改为你自己的 Cookie 安全字符串>;

此时目录结构如下:

  1. egg-example
  2. ├── app
  3. ├── controller
  4. └── home.js
  5. └── router.js
  6. ├── config
  7. └── config.default.js
  8. └── package.json

完整的目录结构规范参见目录结构

好,现在可以启动应用来体验下

  1. $ npm run dev
  2. $ open localhost:7001

注意:

  • Controller 有 classexports 两种编写方式,本文示范的是前者,你可能需要参考 Controller 文档。
  • Config 也有 module.exportsexports 的写法,具体参考 Node.js modules 文档

静态资源

Egg 内置了 static 插件,线上环境建议部署到 CDN,无需该插件。

static 插件默认映射 /public/* -> app/public/* 目录

此处,我们把静态资源都放到 app/public 目录即可:

  1. app/public
  2. ├── css
  3. └── news.css
  4. └── js
  5. ├── lib.js
  6. └── news.js

模板渲染

绝大多数情况,我们都需要读取数据后渲染模板,然后呈现给用户。故我们需要引入对应的模板引擎。

框架并不强制你使用某种模板引擎,只是约定了 View 插件开发规范,开发者可以引入不同的插件来实现差异化定制。

更多用法参见 View

在本例中,我们使用 Nunjucks 来渲染,先安装对应的插件 egg-view-nunjucks

  1. $ npm i egg-view-nunjucks --save

开启插件:

  1. // config/plugin.js
  2. exports.nunjucks = {
  3. enable: true,
  4. package: 'egg-view-nunjucks'
  5. };
  1. // config/config.default.js
  2. exports.keys = <此处改为你自己的 Cookie 安全字符串>;
  3. // 添加 view 配置
  4. exports.view = {
  5. defaultViewEngine: 'nunjucks',
  6. mapping: {
  7. '.tpl': 'nunjucks',
  8. },
  9. };

注意:是 config 目录,不是 app/config!

为列表页编写模板文件,一般放置在 app/view 目录下

  1. <!-- app/view/news/list.tpl -->
  2. <html>
  3. <head>
  4. <title>Hacker News</title>
  5. <link rel="stylesheet" href="/public/css/news.css" />
  6. </head>
  7. <body>
  8. <ul class="news-view view">
  9. {% for item in list %}
  10. <li class="item">
  11. <a href="{{ item.url }}">{{ item.title }}</a>
  12. </li>
  13. {% endfor %}
  14. </ul>
  15. </body>
  16. </html>

添加 Controller 和 Router

  1. // app/controller/news.js
  2. const Controller = require('egg').Controller;
  3. class NewsController extends Controller {
  4. async list() {
  5. const dataList = {
  6. list: [
  7. { id: 1, title: 'this is news 1', url: '/news/1' },
  8. { id: 2, title: 'this is news 2', url: '/news/2' }
  9. ]
  10. };
  11. await this.ctx.render('news/list.tpl', dataList);
  12. }
  13. }
  14. module.exports = NewsController;
  15. // app/router.js
  16. module.exports = app => {
  17. const { router, controller } = app;
  18. router.get('/', controller.home.index);
  19. router.get('/news', controller.news.list);
  20. };

启动浏览器,访问 http://localhost:7001/news 即可看到渲染后的页面。

提示:开发期默认开启了 development 插件,修改后端代码后,会自动重启 Worker 进程。

编写 service

在实际应用中,Controller 一般不会自己产出数据,也不会包含复杂的逻辑,复杂的过程应抽象为业务逻辑层 Service

我们来添加一个 Service 抓取 Hacker News 的数据 ,如下:

  1. // app/service/news.js
  2. const Service = require('egg').Service;
  3. class NewsService extends Service {
  4. async list(page = 1) {
  5. // read config
  6. const { serverUrl, pageSize } = this.config.news;
  7. // use build-in http client to GET hacker-news api
  8. const { data: idList } = await this.ctx.curl(`${serverUrl}/topstories.json`, {
  9. data: {
  10. orderBy: '"$key"',
  11. startAt: `"${pageSize * (page - 1)}"`,
  12. endAt: `"${pageSize * page - 1}"`,
  13. },
  14. dataType: 'json',
  15. });
  16. // parallel GET detail
  17. const newsList = await Promise.all(
  18. Object.keys(idList).map(key => {
  19. const url = `${serverUrl}/item/${idList[key]}.json`;
  20. return this.ctx.curl(url, { dataType: 'json' });
  21. })
  22. );
  23. return newsList.map(res => res.data);
  24. }
  25. }
  26. module.exports = NewsService;

框架提供了内置的 HttpClient 来方便开发者使用 HTTP 请求。

然后稍微修改下之前的 Controller:

  1. // app/controller/news.js
  2. const Controller = require('egg').Controller;
  3. class NewsController extends Controller {
  4. async list() {
  5. const ctx = this.ctx;
  6. const page = ctx.query.page || 1;
  7. const newsList = await ctx.service.news.list(page);
  8. await ctx.render('news/list.tpl', { list: newsList });
  9. }
  10. }
  11. module.exports = NewsController;

还需增加 app/service/news.js 中读取到的配置:

  1. // config/config.default.js
  2. // 添加 news 的配置项
  3. exports.news = {
  4. pageSize: 5,
  5. serverUrl: 'https://hacker-news.firebaseio.com/v0',
  6. };

编写扩展

遇到一个小问题,我们的资讯时间的数据是 UnixTime 格式的,我们希望显示为便于阅读的格式。

框架提供了一种快速扩展的方式,只需在 app/extend 目录下提供扩展脚本即可,具体参见扩展

在这里,我们可以使用 View 插件支持的 Helper 来实现:

  1. $ npm i moment --save
  1. // app/extend/helper.js
  2. const moment = require('moment');
  3. exports.relativeTime = time => moment(new Date(time * 1000)).fromNow();

在模板里面使用:

  1. <!-- app/view/news/list.tpl -->
  2. {{ helper.relativeTime(item.time) }}

编写 Middleware

假设有个需求:我们的新闻站点,禁止百度爬虫访问。

聪明的同学们一定很快能想到可以通过 Middleware 判断 User-Agent,如下:

  1. // app/middleware/robot.js
  2. // options === app.config.robot
  3. module.exports = (options, app) => {
  4. return async function robotMiddleware(ctx, next) {
  5. const source = ctx.get('user-agent') || '';
  6. const match = options.ua.some(ua => ua.test(source));
  7. if (match) {
  8. ctx.status = 403;
  9. ctx.message = 'Go away, robot.';
  10. } else {
  11. await next();
  12. }
  13. }
  14. };
  15. // config/config.default.js
  16. // add middleware robot
  17. exports.middleware = [
  18. 'robot'
  19. ];
  20. // robot's configurations
  21. exports.robot = {
  22. ua: [
  23. /Baiduspider/i,
  24. ]
  25. };

现在可以使用 curl http://localhost:7001/news -A "Baiduspider" 看看效果。

更多参见中间件文档。

配置文件

写业务的时候,不可避免的需要有配置文件,框架提供了强大的配置合并管理功能:

  • 支持按环境变量加载不同的配置文件,如 config.local.jsconfig.prod.js 等等。
  • 应用/插件/框架都可以配置自己的配置文件,框架将按顺序合并加载。
  • 具体合并逻辑可参见配置文件
  1. // config/config.default.js
  2. exports.robot = {
  3. ua: [
  4. /curl/i,
  5. /Baiduspider/i,
  6. ],
  7. };
  8. // config/config.local.js
  9. // only read at development mode, will override default
  10. exports.robot = {
  11. ua: [
  12. /Baiduspider/i,
  13. ],
  14. };
  15. // app/service/some.js
  16. const Service = require('egg').Service;
  17. class SomeService extends Service {
  18. async list() {
  19. const rule = this.config.robot.ua;
  20. }
  21. }
  22. module.exports = SomeService;

单元测试

单元测试非常重要,框架也提供了 egg-bin 来帮开发者无痛的编写测试。

测试文件应该放在项目根目录下的 test 目录下,并以 test.js 为后缀名,即 {app_root}/test/**/*.test.js

  1. // test/app/middleware/robot.test.js
  2. const { app, mock, assert } = require('egg-mock/bootstrap');
  3. describe('test/app/middleware/robot.test.js', () => {
  4. it('should block robot', () => {
  5. return app.httpRequest()
  6. .get('/')
  7. .set('User-Agent', "Baiduspider")
  8. .expect(403);
  9. });
  10. });

然后配置依赖和 npm scripts

  1. {
  2. "scripts": {
  3. "test": "egg-bin test",
  4. "cov": "egg-bin cov"
  5. }
  6. }
  1. $ npm i egg-mock --save-dev

执行测试:

  1. $ npm test

就这么简单,更多请参见 单元测试

后记

短短几章内容,只能讲 Egg 的冰山一角,我们建议开发者继续阅读其他章节:

  • 关于骨架类型,参见骨架说明
  • 提供了强大的扩展机制,参见插件
  • 一个大规模的团队需要遵循一定的约束和约定,在 Egg 里我们建议封装适合自己团队的上层框架,参见 框架开发
  • 这是一个渐进式的框架,代码的共建,复用和下沉,竟然可以这么的无痛,建议阅读 渐进式开发
  • 写单元测试其实很简单的事,Egg 也提供了非常多的配套辅助,我们强烈建议大家测试驱动开发,具体参见 单元测试