LoginSignup
8
4

More than 5 years have passed since last update.

TypeScriptで書いたCloud FunctionsをCloudBuildを使ってDeployする

Last updated at Posted at 2018-10-09

これを読んで出来るようになること

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の設定

スクリーンショット 2018-10-09 13.56.09.png

動作確認

$ 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するとファイルサイズが大きくなる

残タスク

8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4