Skip to content

docs: re-write of the typescript user guide #489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 19, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 99 additions & 70 deletions docs/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,73 +3,102 @@
This guide is an example of how to develop a function in Typescript with
the Functions Framework.

1. Use [gts](https://github.com/google/gts) to configure Typescript.

```sh
npx gts init
```

2. Install the required packages:

```sh
npm install @google-cloud/functions-framework
npm install @types/express concurrently nodemon --save-dev
```

3. Add a `start` script to `package.json`, passing in the `--source` flag to
point to the compiled code directory (configured by `gts` in this example).
Also add a `watch` script to use for development:

```js
"scripts": {
"start": "functions-framework --source=build/src/ --target=helloWorld",
"watch": "concurrently \"tsc -w\" \"nodemon --watch ./build/ --exec npm run start\"",
...
}
```

4. Replace the contents of `src/index.ts` with:

```ts
import type { HttpFunction } from '@google-cloud/functions-framework/build/src/functions';

export const helloWorld: HttpFunction = (req, res) => {
res.send('Hello, World');
};
```

5. Start the built-in local development server in watch mode:

```sh
npm run watch
```

This will continuously watch changes to your TypeScript project and recompile when changes are detected:

```sh
[12:34:56 AM] Starting compilation in watch mode...
[12:34:57 AM] Found 0 errors. Watching for file changes.
...
Serving function...
Function: helloWorld
URL: http://localhost:8080/
```

## Deploying with gcloud CLI

1. Adjust `main` field in `package.json` to point to the compiled javascript source.

```js
"main": "build/src/index.js",
...
```

1. Remove `prepare` script in `package.json` created by [gts](https://github.com/google/gts). This is because the `prepare` script requires typescript to be installed and will cause the function to fail to deploy if not removed.

1. Deploy:

```sh
gcloud functions deploy helloWorld \
--runtime nodejs16 \
--trigger-http
```
1. Create a new Node.js project using the npm CLI.

```sh
mkdir typescript-function && cd typescript-function
npm init -y
```

1. Install the required packages:

```sh
npm install @google-cloud/functions-framework
npm install --save-dev typescript
```

1. Create a `tsconfig.json` in the root directory of your project with the following contents:

```json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
```

1. Update your `package.json` with scripts for building and running your application:

```json
{
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "functions-framework --target=TypescriptFunction",
"prestart": "npm run build",
"gcp-build": "npm run build"
},
...
}
```

- The `main` field must be configured to the compiled source code file that contains your function source.
- The [`gcp-build` script](https://cloud.google.com/functions/docs/writing/specifying-dependencies-nodejs#executing_custom_build_steps_during_deployment) is run when deploying your application Google Cloud Functions. It allows you to configure build steps that depend on `devDependencies`.

1. Create a `.gitignore` that ensures your `node_modules` and compiled code are not checked into source control and are not uploaded when you deploy to Google Cloud Functions.

```
node_modules/
dist/
```

1. Create a `src/index.ts` file with your function source code.

**Example Typescript HTTP Function**

```typescript
import * as ff from '@google-cloud/functions-framework';

ff.http('TypescriptFunction', (req: ff.Request, res: ff.Response) => {
res.send('OK');
});
```

**Example Typescript CloudEvent Function**

The `cloudEvent` function registration method accepts a template type that can be used to
annotate the event payload type you expect.

```typescript
import ff from '@google-cloud/functions-framework';

interface PubSubData {
subscription: string;
message: {
messageId: string;
publishTime: string;
data: string;
attributes?: {[key: string]: string};
};
}

ff.cloudEvent<PubSubData>('TypescriptFunction', ce => {
console.log(ce.data?.message.messageId);
});
```

## Deploying with the gcloud CLI

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it might be useful to have instructions for running the function locally.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure I can do that.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks


If you correctly configured the `main` field and `gcp-build` script in your `package.json` you can deploy to Google Cloud Functions as you would any other Javascript function:

```sh
gcloud functions deploy TypescriptFunction \
--runtime nodejs16 \
--trigger-http
```