To develop a function using TypeScript with the Functions Framework, follow these steps to set up your project environment, compiler, and build scripts.
Initialize the project:
mkdir typescript-function && cd typescript-function
npm init -y
Install dependencies:
Install the framework and TypeScript as a development dependency:
npm install @google-cloud/functions-framework
npm install --save-dev typescript
Configure TypeScript:
Create a tsconfig.json in your root directory:
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Configure package.json:
Set the main field to your compiled entry point (e.g., dist/index.js) and add scripts for building and running. Use the gcp-build script to ensure devDependencies like typescript are used during deployment on Google Cloud Functions.
{
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "functions-framework --target=TypescriptFunction",
"prestart": "npm run build",
"gcp-build": "npm run build"
}
}
Configure .gitignore:
Ensure node_modules/ and your output directory (e.g., dist/) are ignored to prevent them from being uploaded during deployment.
node_modules/
dist/