これを読んで出来るようになること
TypeScriptで書いたCloud Functionを、Code Buildを使ってdeployできるようになる。
前提と事前準備
前提
- CloudFunctionsのコードはwebpackを使ってまとめている
- Deployは serverless コマンドではなく、gcloudコマンドで行っている
事前準備
テスト用リポジトリ: https://github.com/selmertsx/cloud_source_repository_test
設定
ディレクトリ構造
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のサンプルコード
webpackを使って、コードが正しくimport出来ていることを確認するために decimal.js
をimportした。
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の設定
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の設定
webpack.config.js
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の設定を勉強