对于稍微大型的 Node 应用,typescript
已是标配,它为 javascript
提供了强类型的铠甲,有效提升了代码质量。javascript
这里是一个结合 ts
及 koa
快速部署到腾讯云函数计算中的模板。仓库以下html
使用本模板快速建立应用java
$ serverless install --url https://github.com/shfshanyue/serverless-template-zh/tree/master/tencent-koa-ts --name koa-server
复制代码
在项目建立早期尽量对 package 进行升级,这里使用了 npm-check-updates
node
$ npm run ncu
复制代码
在测试环境中进行开发ios
$ npm run dev
复制代码
.
├── dist/ # 编译文件,及最终须要上传的目录
├── node_modules/
├── app.ts # 入口文件,必须采用 app 的命名
├── package.json
├── package-lock.json
├── Readme.md
├── serverless.yaml # serverless 配置文件
└── tsconfig.json
复制代码
app.ts
便是你业务逻辑的入口文件,你能够像其余 Koa Application 同样自由组织路由,业务逻辑,Model 等。git
import Koa from 'koa'
const app = new Koa()
app.use(async (ctx, next) => {
ctx.body = `hello, path: '${ctx.request.path}'`
})
app.listen(3333, () => { console.log('Listening 3333') })
module.exports = app
复制代码
serverless component
能够认为是把 faas 及 baas 资源集合的进一步抽象,该项目采用了 @serverless/tencent-koa
github
koa-app:
component: '@serverless/tencent-koa'
inputs:
region: ap-guangzhou
functionName: koa-function
runtime: Nodejs10.15
code: ./dist
functionConf:
timeout: 60
memorySize: 128
apigatewayConf:
protocols:
- https
environment: release
复制代码
部署以前须要准备好生产环境所需的 node_modules
以及编译完成的 js 资源。typescript
# 装包
$ npm install typescript
# 编译成 js
$ npm run build
# 打包生产环境的包,并移至 dist 目录
# predeploy: npm ci --production && rsync -avz node_modules dist/
$ npm run predeploy
# 部署到腾讯云
$ sls
koa-function [████████████████████████████████████████] 100% | ETA: 0s | Speed: 314.98k/
koa-app:
functionName: koa-function
functionOutputs:
ap-guangzhou:
Name: koa-function
Runtime: Nodejs10.15
Handler: serverless-handler.handler
MemorySize: 128
Timeout: 60
Region: ap-guangzhou
Namespace: default
Description: This is a function created by serverless component
region: ap-guangzhou
apiGatewayServiceId: service-dture22u
url: https://service-dture22u-1257314149.gz.apigw.tencentcs.com/release/
cns: (empty array)
11s › koa-app › done
复制代码
从日志能够看出,部署到腾讯云只需 11s,仍是很快速npm
在本地直接使用 npm run dev
,在本地端口调试。而在生产环境,使用 sls 部署后日志中提供的 url 进行 http 调用json
$ curl https://service-dture22u-1257314149.gz.apigw.tencentcs.com/release/
hello, path: '/'#
复制代码
在开始以前,稍微提一下缺点:
log
及 metrics
,须要转至腾讯云控制台查看因为部署过程稍微复杂,能够考虑重写一个关于 ts 的 serverless component