초기화가 완료되면 index.ts에서 샘플의 주석 처리를 삭제하고 npm run serve를 실행하여 'Hello World' 함수가 작동하는 것을 확인합니다.
기존 TypeScript 프로젝트 사용
기존 TypeScript 프로젝트가 있는 경우 배포 전 후크를 추가하면 Cloud Functions for Firebase로 코드를 배포할 때마다 프로젝트를 변환 컴파일할 수 있습니다. 올바르게 구성된 tsconfig.json 파일과 Firebase 프로젝트가 필요하며 Firebase 구성을 다음과 같이 수정해야 합니다.
package.json을 편집하여 TypeScript 프로젝트를 빌드하는 bash 스크립트를 추가합니다. 예를 들면 다음과 같습니다.
{"name":"functions","scripts":{"build":"npm run lint && tsc"}...
firebase.json을 편집하여 빌드 스크립트를 실행하기 위한 배포 전 후크를 추가합니다. 예를 들면 다음과 같습니다.
{"functions":{"predeploy":"npm --prefix functions run build",}}
이 구성을 사용하면 firebase deploy --only functions 명령어가 TypeScript 코드를 빌드하여 함수로 배포합니다.
기존 자바스크립트 프로젝트를 TypeScript로 마이그레이션
자바스크립트로 초기화하고 개발한 기존 Cloud Functions 프로젝트가 있는 경우 TypeScript로 마이그레이션할 수 있습니다. 시작하기 전에 git 체크포인트 등의 백업을 만들어 두는
것이 좋습니다.
기존 JavaScript Cloud Functions 프로젝트를 마이그레이션하는 방법:
git 체크포인트를 만들고 기존 자바스크립트 소스 파일의 복사본을 저장합니다.
프로젝트 디렉터리에서 firebase init functions를 실행하고 함수 작성 언어를 묻는 메시지가 표시되면 TypeScript를 선택합니다.
기존 package.json 파일을 덮어쓸지 묻는 메시지가 표시되면 기존 파일이 확실히 필요 없는 경우를 제외하고는 아니요를 선택합니다.
functions/src 디렉터리에서 index.ts를 삭제하고 기존 소스 코드로 대체합니다.
초기화 시 생성된 tsconfig.json 파일에서 자바스크립트를 허용하는 컴파일러 옵션("allowJs": true)을 설정합니다.
저장된 package.json 파일을 functions 디렉터리에 복사하고 수정하여 "main"을 "lib/index.js"로 설정합니다.
또한 package.json에서 다음과 같이 TypeScript용 빌드 스크립트를 추가합니다.
{"name":"functions","scripts":{"build":"npm run lint && tsc"}...
모든 종속 항목에 대해 npm install --save @types/<dependency>를 실행합니다.
.js 소스 코드를 필요에 따라 .ts로 재작성합니다.
TypeScript 함수 에뮬레이션
TypeScript 함수를 로컬로 테스트하려면 로컬에서 함수 실행에서 설명한 에뮬레이션 도구를 사용할 수 있습니다. 이러한 도구를 사용하기 전에 코드를 컴파일하는 것이 중요합니다. 따라서 firebase emulators:start 또는 firebase functions:shell을 실행하기 전에 함수 디렉터리 내에서 npm run build를 실행합니다. 또는 npm run serve 또는 npm run shell을 바로가기로 실행합니다. 이 명령어는 둘 다 빌드를 실행하고 함수 셸을 제공/시작합니다.
TypeScript 프로젝트의 함수 로그
firebase deploy 실행 중에 프로젝트의 index.ts가 index.js로 변환 컴파일됩니다. 즉, Cloud Functions 로그에는 내가 작성한 코드가 아닌 index.js 파일의 줄 번호가 출력됩니다. firebase deploy는 해당 경로와 줄 번호를 index.ts에서 쉽게 찾을 수 있도록 functions/lib/index.js.map을 만듭니다. 원하는 IDE에서 또는 node 모듈을 통해 이 소스 맵을 사용할 수 있습니다.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-05(UTC)"],[],[],null,["\u003cbr /\u003e\n\nFor developers who prefer to write functions in TypeScript,\nCloud Functions provides two types of support:\n\n- Create and configure TypeScript projects for automatic transpilation at initialization (`firebase init functions`).\n- Transpile existing TypeScript source to JavaScript at deploy time via a [predeploy hook](/docs/cli#hooks).\n\nFollowing instructions in this guide, you can migrate an existing\nJavaScript project to TypeScript and continue deploying functions using a\npredeploy hook to transpile your source code.\nTypeScript offers many benefits over vanilla JavaScript\nwhen writing functions:\n\n- TypeScript supports latest JavaScript features like async/await, simplifying promise management\n- A Cloud Functions linter highlights common problems while you're coding\n- Type safety helps you avoid runtime errors in deployed functions\n\nIf you're new to TypeScript, see [TypeScript in 5 minutes](http://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html).\n\nInitializing a new Cloud Functions project with TypeScript\n\nRun `firebase init functions` in a new directory. The tool gives you options to build\nthe project with JavaScript or TypeScript. Choose **TypeScript** to output the\nfollowing project structure: \n\n myproject\n +- functions/ # Directory containing all your functions code\n |\n +- package.json # npm package file describing your Cloud Functions code\n |\n +- tsconfig.json\n |\n +- .eslintrc.js # Optional file if you enabled ESLint\n +- tsconfig.dev.json # Optional file that references .eslintrc.js\n |\n +- src/ # Directory containing TypeScript source\n | |\n | +- index.ts # main source file for your Cloud Functions code\n |\n +- lib/\n |\n +- index.js # Built/transpiled JavaScript code\n |\n +- index.js.map # Source map for debugging\n\nOnce initialization is complete, uncomment the sample in index.ts and run\n`npm run serve` to see a \"Hello World\" function in action.\n\nUsing an existing TypeScript project\n\nIf you have an existing TypeScript project, you can add a predeploy hook to\nmake sure your project is transpiled every time you deploy your code to\nCloud Functions for Firebase. You'll need a\nproperly formed `tsconfig.json` file and a Firebase project, and you'll need\nto make the following modifications to your Firebase configuration:\n\n1. Edit `package.json` to add a bash script to build your TypeScript project. For example:\n\n {\n \"name\": \"functions\",\n \"scripts\": {\n \"build\": \"npm run lint && tsc\"\n }\n ...\n\n2. Edit `firebase.json` to add a predeploy hook to run the build script. For example:\n\n {\n \"functions\": {\n \"predeploy\": \"npm --prefix functions run build\",\n }\n }\n\nWith this configuration, a `firebase deploy --only functions` command\nbuilds your TypeScript code and deploys it as functions.\n\nMigrating an existing JavaScript project to TypeScript\n\nIf you have an existing Cloud Functions project that you initialized\nand developed in JavaScript, you can migrate it to\nTypeScript. You're strongly encouraged to create a git checkpoint or other\nbackup before starting.\n\n**To migrate an existing JavaScript Cloud Functions project:**\n\n1. Create a git checkpoint and save copies of your existing JavaScript source files.\n2. In the project directory, run `firebase init functions` and select `TypeScript` when prompted for a language for writing functions.\n3. When prompted whether to overwrite the existing `package.json` file, select **No** unless you are sure you don't want to keep the existing file.\n4. Delete `index.ts` in the directory `functions/src`, replacing it with your existing source code.\n5. In the `tsconfig.json` file created at initialization, set the compiler options to allow JavaScript: `\"allowJs\": true`.\n6. Copy your saved `package.json` file into the `functions` directory, and edit it to set `\"main\"` to `\"lib/index.js\"`.\n7. Also in `package.json`, add a build script for TypeScript like the following:\n\n {\n \"name\": \"functions\",\n \"scripts\": {\n \"build\": \"npm run lint && tsc\"\n }\n ...\n\n8. Add `\"typescript\"` as a dev dependency by running `npm install --save-dev typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser`.\n\n9. For all dependencies, run `npm install --save @types/\u003cdependency\u003e`.\n\n10. Rewrite source code from .js to .ts as desired.\n\nEmulating TypeScript functions\n\nTo test TypeScript functions locally, you can use the emulation tools described\nin [Run functions locally](/docs/functions/local-emulator). It's important to\ncompile your code before using these tools, so make sure to run `npm run build`\ninside your functions directory before running `firebase emulators:start` or\n`firebase functions:shell`. Alternatively, run `npm run serve` or\n`npm run shell` as a shortcut; these commands both run the build and\nserve/start the functions shell.\n\nFunctions logs for TypeScript projects\n\nDuring `firebase deploy`, your project's `index.ts` is transpiled to `index.js`,\nmeaning that the Cloud Functions log will output line numbers from the\n`index.js` file and not the code you wrote. To make it easier for you to find the\ncorresponding paths and line numbers in `index.ts`,\n`firebase deploy` creates `functions/lib/index.js.map`. You can use this source\nmap in your preferred IDE or via a [node module](https://github.com/evanw/node-source-map-support)."]]