egg.js 的项目初始化
egg.js官网:https://eggjs.org/zh-cn/index.html
//脚手架
$ npm install egg-init -g
//egg 的项目初始化
$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
配置渲染模板
npm i egg-view-nunjucks --save
修改默认的的配置文件
config/plugin.js
//初始时的文件
module.exports = {
// had enabled by egg
// static: {
// enable: true,
// }
};
//修改后的文件
exports.nunjucks = {
enable: true,
package: 'egg-view-nunjucks'
};
config/config.default.js
//初始化时的文件
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1569550138064_1554';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
return {
...config,
...userConfig,
};
};
//配置模板渲染后的文件
/* eslint valid-jsdoc: "off" */
'use strict';
/**
* @param {Egg.EggAppInfo} appInfo app info
*/
module.exports = appInfo => {
/**
* built-in config
* @type {Egg.EggAppConfig}
**/
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1569550138064_1554';
// add your middleware config here
config.middleware = [];
// add your user config here
const userConfig = {
// myAppName: 'egg',
};
// 选软模板渲染
config.view = {
defaultViewEngine: 'nunjucks',
mapping: {
'.html': 'nunjucks',
},
};
return {
...config,
...userConfig,
};
};
router的配置
// app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.get('/list', controller.news.list);
};
页面的请求数据
// app/controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
let title = "我是首页"; //向模板传入数据
await this.ctx.render('index.html',{
title: title
});
}
}
module.exports = HomeController;
html的页面数据绑定
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{{ title }}</title>
</head>
<body>
<!-- 使用模板数据 -->
<h1>{{ title }}</h1>
<!-- 使用模板数据 -->
<h2>欢迎来到egg</h2>
</body>
</html>
创建ts类型的
npm init egg --type=ts //创建ts写的提示项目
// 项目的发布
// 所有文件发布服务器,在服务器上安装8.9.0 以上版本的node
npm i
npm run tsc //编译成js文件
npm start