美文网首页
【原创】快速搭建egg.js

【原创】快速搭建egg.js

作者: 麻烦来一大碗猫 | 来源:发表于2019-05-13 18:57 被阅读0次

快速初始化

安装egg.js脚手架

    npm i -g egg-init

初始化egg.js应用

    egg-init egg-example --type=simple

安装应用依赖

   cd egg-example
   npm i

启动项目

    npm run dev

在localhost:7001端口打开应用

Nunjucks渲染

本地安装egg-view-nunjucks插件

    npm i egg-view-nunjucks --save

在应用里开启nunjucks插件

    // config/plugin.js
    exports.nunjucks = {
        enable: true,
        package: 'egg-view-nunjucks'
    };

配置nunjucks插件

    // 添加view配置
    exports.view={
        defaultViewEngine: 'nunjucks',
        mapping: {
            '.tpl': 'nunjucks',
        },
    };

编写模板文件

<!--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>

添加Controller

    <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>

添加路由Router

    //app/router.js
    module.exports = app => {
        const { router, controller } = app;
        router.get('/', controller.home.index);
        router.get('/news', controller.news.list);
    };

相关文章

网友评论

      本文标题:【原创】快速搭建egg.js

      本文链接:https://www.haomeiwen.com/subject/cvgraqtx.html