koa项目构建
初始化项目
yarn init -y
yarn add koa
配置启动文件app.js
const Koa = require('koa')
const app = new Koa()
app.use(ctx => {
ctx.body = 'hello'
})
app.listen(3000)
配置环境变量(区分开发和生产环境)
config/index.js
yarn add lodash
const { extend } = require("lodash")
const baseConfig = {}
if (process.env.NODE_ENV == "development") {
const localConfig = {
port: 8081
}
baseConfig = extend(baseConfig, localConfig)
}
if (process.env.NODE_ENV == "production") {
const prodConfig = {
port: 80
}
baseConfig = extend(baseConfig, prodConfig)
}
module.exports = baseConfig
修改app.js监听接口来自与配置文件
const {port} = require('./config')
app.listen(port)
需要只能指定环境变量
cross-env, 运行跨平台设置和使用环境变量的脚本
yarn add cross-env
添加脚本”server:start”: “cross-env NODE_ENV=development ./app.js”
自动重启(热更新)
yarn add nodemon —dev
修改脚本 “server:start”: “cross-env NODE_ENV=development nodemon ./app.js”,
启动 yarn server:start
配置路由
yarn add koa-simple-router
app.js 中添加
const router = require('koa-simple-router')
app.use(router(_ => {
_.get('/', (ctx, next) => {
ctx.body = 'hello'
})
_.post('/name/:id', (ctx, next) => {
// ...
})
})
分离controller
app.js 添加路由组册中心
require("./controllers")(app)
controller/index.js
const router = require('koa-simple-router')
const BookController = require("./BooksController")
const bookController = new BookController()
const IndexController = require("./IndexController")
const indexController = new IndexController()
module.exports = app => {
app.use(router(_ => {
// 伪静态
_.get('/', indexController.actionIndex)
_.get('/books/list', bookController.actionIndex)
}))
}
添加 controllers/BooksController
class IndexController {
constructor() {
}
actionIndex(ctx, next) {
ctx.body = {
data: ' 首页'
}
}
}
module.exports = IndexController
首页, 访问 localhost:8081/ 。列表页, 访问 localhost:8081/books/list。
分离Models
添加 models/Books
class Books {
constructor(app) {
this.app = app
}
getData(options) {
return Promise.resolve("数据请求成功")
}
}
修改actionIndex
async actionIndex(ctx, next) {
const books = new Books()
const result = await books.getData();
ctx.body = result
}
生成文档
jsdoc/swagger, vscode插件jsdoc风格注释
yarn add jsdoc —dev
添加脚本 “api:docs”: “jsdoc ./*/.js -d ./docs/jsdoc”
配置别名
// 别名 module-alias
yarn add module-alias
app.js 顶部添加
const moduleAlias = require("module-alias")
moduleAlias.addAliases({
'@root': __dirname,
'@controllers': __dirname+'/controllers',
'@models': __dirname+'/models'
})
MPA
模版语言
// SSR - 借助模版语言koa2-swig(缓存好)
yarn add koa2-swig
// co 辅助
yarn add co
var render = require('koa-swig');
const co = require("co")
app.context.render = co.wrap(render({
// root: path.join(__dirname, 'views'),
root: viewDir,
autoescape: true,
// cache: 'memory', // disable, set to false
cache: process.env.NODE_ENV == "development" ? false : 'memory',
ext: 'html',
// locals: locals,
// filters: filters,
// tags: tags,
// extensions: extensions
writeBody: false
}));
模版语言
创建views/layout.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<head>
<meta charset="utf-8" />
<title>
{% block title %}{% endblock %}
</title>
{% block style %}{% endblock %}
</head>
</head>
<body>
{% block content %}{% endblock %}
{% block script %}{% endblock %}
</body>
</html>
创建 views/index.html
{% extends './layout.html' %}
{% block title %}
首页
{% endblock %}
{% block content %}
<h1>首页</h1>
{% endblock %}
{% block script %}
<script>
console.log('本地log')
</script>
{% endblock %}
引入外部资源(js/css)
yarn add koa-static
app.js 添加
const serve = require('koa-static')
app.use(serve(path.join(__dirname, 'assets')))
index.html中添加 外部资源引入
{% block style %}
<link rel="stylesheet" type="text/css" href="/styles/index.css" />
<style>
.gray-text{
color: #eee;
}
</style>
{% endblock %}
{% block script %}
<script src="/scripts/index.js" ></script>
<script>
console.log('本地log')
</script>
{% endblock %}
创建assets/scripts/index.js
创建assets/styles/index.css
模版冲突
与vue中{{ }}
解决方案一:模版render中添加
app.context.render = render({
varControls: ["[[", "]]"]// 双花括号冲突
})
解决方案二:修改vue的编译格式
new Vue({
delimiters:['$$','$$'],
})
MPA+SPA,vue项目继集成
ApiController.js
前端路由(SPA), 靠js驱动
后端路由 (MPA)
pushstate
需要区分前后端路由
// koa2-connect-history-api-fallback, 添加白名单
yarn add koa2-connect-history-api-fallback
压测swig缓存优势,qps
搭建vue工程
// 检查node和npm版本
node/npm --version
yarn global add @vue/cli
yarn info @vue/cli version
vue --version
vue create homework-books
$ cd homework-books
$ yarn serve