Using TypeScript with Google Cloud Functions without compiling
Published in
2 min readMar 31, 2022
When using TypeScript in GCF, you need to compile it, but since I forget to compile it or it is a pain to manage the compilation artifacts, I looked for a way to run it as is, but could not find any information.
In this article, I would like to show you how I achieved this using ts-node.
Prepare
Creating a node.js application
$ npm init
Module Installation
$ npm install typescript ts-node @types/express
$ npm install - save-dev nodemon @google-cloud/functions-framework
Generate “. /tsconfig.json”
$ npx tsc - init
Add the following “script” to “./package.json”
{
"name": "hello-world",
"version": "1.0.0",
"main": "index.js",
"private": true,
"scripts": {
"start": "functions-framework --target=helloWorld",
"watch": "nodemon --watch ./src/ --ext ts,js,mjs,json --exec npm run start"
},
"dependencies": {
"@types/express": "^4.17.13",
"ts-node": "^10.7.0",
"typescript": "^4.6.3"
},
"devDependencies": {
"@google-cloud/functions-framework": "^3.0.0",
"nodemon": "^2.0.15"
}
}
Make `./index.js` as follows
const scriptPath = "./src/index.ts";
// Import the ts file of scriptPath
require("ts-node/dist/bin").main([
// "--compiler-options",
// JSON.stringify({
// target: "ES2017",
// module: "CommonJS",
// }),
scriptPath,
]);
// Assign scriptPath default to exports.helloWorld
exports.helloWorld = require(scriptPath).default;
Make `./src/index.js` as follows
import type { Request, Response } from 'express';
export default (req: Request, res: Response) => {
res.send("Hello, World");
};
Run locally
Start locally
$ npm run watch
When you open http://localhost:8080/, you will see “Hello World”.
$ curl http://localhost:8080/
Hello, World
Deploy
Execute the deploy command.
$ gcloud functions deploy helloWorld --runtime=nodejs16 --trigger-http --region=asia-northeast1