TypeScriptで書いたCloud FunctionsをCloudBuildを使ってDeployする
これを読んで出来るようになること
TypeScriptで書いたCloud Functionを、Code Buildを使ってdeployできるようになる。
前提と事前準備
前提
- CloudFunctionsのコードはwebpackを使ってまとめている
- Deployは serverless コマンドではなく、gcloudコマンドで行っている
事前準備
過去の記事
設定
ディレクトリ構造
cloud_source_repository_test git:(master) tree -I node_modules ├── README.md ├── cloudbuild.yaml ├── package-lock.json ├── package.json ├── src │ └── index.ts ├── tsconfig.json └── webpack.config.js
TypeScriptのサンプルコード
import { Decimal } from "decimal.js"; function subscribe(req: any, res: any){ const x = new Decimal('0xff.f') return res.send(`Hello World! ${x}`); } export { subscribe }
cloudbuild.yamlの設定
steps: - name: node:8 entrypoint: npm args: - install - name: node:8 entrypoint: npm args: - run - build - name: 'gcr.io/cloud-builders/gcloud' args: - functions - deploy - subscribe - --stage-bucket=xxx - --trigger-http
buildコマンドの中では webpack --mode productionが実行されています。
tsconfig.jsonの設定
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"strict": true,
"preserveConstEnums": true,
"strictNullChecks": true,
"sourceMap": true,
"outDir": "./",
"moduleResolution": "node",
"esModuleInterop": true
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
Webpackの設定
module.exports = {
entry: "./src/index.ts",
target: 'node',
output: {
path: __dirname,
filename: 'index.js',
libraryTarget: 'this'
},
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader'
}
]
},
resolve: {
extensions: [ '.js', '.json' ]
}
}
IAM Roleの設定

動作確認
$ curl https://xxx.cloudfunctions.net/subscribe Hello World! 255.9375%
備考
webpackを利用する理由
- node_modulesも、Cloud Functionにuploadすればwebpackを利用する必要は無い
- CodeBuild内でBuildとdeployをするため、Development環境用のpackageもinstallは必須
- Development環境用のpackageもgcloud コマンドでdeployするとファイルサイズが大きくなる
残タスク
- IAMのカスタムロールを、terraformで作りたい
- debug 用のsourceMapの設定がしたい
- webpackのexternalsの設定を勉強