TypeScript + Node.jsでAPIサービスを5分で作成方法


この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので十分ご注意ください。

概要

TypeScriptは、JavaScriptを拡張して作られたプログラミング言語です。Web開発者にとって知っておくべきことだとなっています。この記事では、ExpressとTypeScriptを使用してNodeサーバーをわずか5分で起動する方法を紹介します。

TypeScriptの設定

まず、プロジェクトフォルダーに作成します。

$ mkdir node-ts-api
$ cd node-ts-api

package.jsonを初期化します。

$ yarn init -y
yarn init v1.22.4
warning The yes flag has been set. This will automatically answer yes to all questions, which may have security implications.
success Saved package.json
Done in 0.05s.

それでは、typescriptパッケージをdev dependencyとしてインストールします。これはアプリを本番環境にデプロイする前に、typescriptで作成したソースをjavascriptにコンパイルするために必要なパッケージです。ご存じの通り、Node.jsはjavascriptのサーバー側の実行環境ですから。

$ yarn add -D typescript
yarn add v1.22.4
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Saved lockfile.
warning Your current version of Yarn is out of date. The latest version is "1.22.5", while you're on "1.22.4".
info To upgrade, download the latest installer at "https://yarnpkg.com/latest.msi".
success Saved 1 new dependency.
info Direct dependencies
└─ typescript@4.2.4
info All dependencies
└─ typescript@4.2.4
Done in 5.35s.

通常、TypeScript言語のプロジェクトでは、ルートディレクトリにtsconfig.jsonファイルが作成する必要です。tsconfig.jsonファイルは、プロジェクトでJavaScriptへのコンパイルが必要となるファイルと、それらのコンパイルオプションなどを指定するファイルです。以下のコマンドを実行してtsconfig.jsonファイルを初期化します。

$ yarn tsc --init --rootDir src --outDir dist
yarn run v1.22.4
$ D:\project\nodejs\node-ts-api\node_modules\.bin\tsc --init --rootDir src --outDir dist
message TS6071: Successfully created a tsconfig.json file.
Done in 0.80s.
$ ls
node_modules/  package.json  tsconfig.json  yarn.lock

初期生成されたtsconfig.jsonファイル内容は以下の通りです。

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    // "lib": [],                                   /* Specify library files to be included in the compilation. */
    // "allowJs": true,                             /* Allow javascript files to be compiled. */
    // "checkJs": true,                             /* Report errors in .js files. */
    // "jsx": "preserve",                           /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "declaration": true,                         /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                      /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                           /* Generates corresponding '.map' file. */
    // "outFile": "./",                             /* Concatenate and emit output to single file. */
    "outDir": "dist",                               /* Redirect output structure to the directory. */
    "rootDir": "src",                               /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                           /* Enable project compilation */
    // "tsBuildInfoFile": "./",                     /* Specify file to store incremental compilation information */
    // "removeComments": true,                      /* Do not emit comments to output. */
    // "noEmit": true,                              /* Do not emit outputs. */
    // "importHelpers": true,                       /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,                  /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                     /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                                 /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                       /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                    /* Enable strict null checks. */
    // "strictFunctionTypes": true,                 /* Enable strict checking of function types. */
    // "strictBindCallApply": true,                 /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,        /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                      /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                        /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                      /* Report errors on unused locals. */
    // "noUnusedParameters": true,                  /* Report errors on unused parameters. */
    // "noImplicitReturns": true,                   /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,          /* Report errors for fallthrough cases in switch statement. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* Module Resolution Options */
    // "moduleResolution": "node",                  /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                             /* Base directory to resolve non-absolute module names. */
    // "paths": {},                                 /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                              /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                             /* List of folders to include type definitions from. */
    // "types": [],                                 /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,        /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                        /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,                    /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,                /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                            /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                               /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                     /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                       /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,              /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,               /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  }
}

上記はあくまでひな型ファイルを作成してもらっています。各プロジェクトは設定する必要な項目が異なるかもしれませんが、基本構成は次のようになります。

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "target": "es5",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    }
  },
  "include": ["src/**/*"]
}

APIの構築

次は必要な追加パッケージをインストールします。サーバーはExpressで構築しますので、最初にExpressパッケージを追加します。

$ yarn add express
yarn add v1.22.4
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Saved lockfile.
success Saved 29 new dependencies.
info Direct dependencies
└─ express@4.17.1
info All dependencies
├─ accepts@1.3.7
├─ array-flatten@1.1.1
├─ body-parser@1.19.0
├─ content-disposition@0.5.3
├─ cookie-signature@1.0.6
├─ cookie@0.4.0
├─ destroy@1.0.4
├─ ee-first@1.1.1
├─ express@4.17.1
├─ finalhandler@1.1.2
├─ forwarded@0.1.2
├─ inherits@2.0.3
├─ ipaddr.js@1.9.1
├─ media-typer@0.3.0
├─ merge-descriptors@1.0.1
├─ methods@1.1.2
├─ mime-db@1.47.0
├─ mime@1.6.0
├─ ms@2.0.0
├─ negotiator@0.6.2
├─ path-to-regexp@0.1.7
├─ proxy-addr@2.0.6
├─ raw-body@2.4.0
├─ safer-buffer@2.1.2
├─ serve-static@1.14.1
├─ type-is@1.6.18
├─ unpipe@1.0.0
├─ utils-merge@1.0.1
└─ vary@1.1.2
Done in 4.49s.

また、開発の便利パッケージのいくつかを追加インストールします。例えば、ソースを監視して、自動でアプリをリビルトとサーバーを再起動してくれるツールのNodemon、tsファイルをコンパイルせずに実行できるようなパッケージのts-nodeなど。

あと、TypeScript の型定義を集めたリポジトリのDefinitelyTypedを利用して、型定義パッケージのインストールです。

Definitely Typed は、間違いなくTypeScriptの最大の強みの一つです。DefinitelyTypeのGitHubリポジトリはnpm パッケージと一緒に @types/xxx というパッケージご提供し、TSのコミュニティによってメンテンナンスして、JavaScript 製のパッケージに対する型定義が大量にあります。これらの型定義は、@types/の形でインストールできます。

CLIで次のコマンドを実行して、typesパッケージ、Nodemon、およびts-nodeをインストールします。

$ yarn add -D @types/node @types/express nodemon ts-node
yarn add v1.22.4
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@2.3.2: The platform "win32" is incompatible with this module.
info "fsevents@2.3.2" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 113 new dependencies.
info Direct dependencies
├─ @types/express@4.17.11
├─ nodemon@2.0.7
└─ ts-node@9.1.1
info All dependencies
├─ @sindresorhus/is@0.14.0
├─ @szmarczak/http-timer@1.1.2
├─ @types/body-parser@1.19.0
├─ @types/connect@3.4.34
├─ @types/express-serve-static-core@4.17.19
├─ @types/express@4.17.11
├─ @types/mime@1.3.2
├─ @types/range-parser@1.2.3
├─ @types/serve-static@1.13.9
├─ abbrev@1.1.1
├─ ansi-align@3.0.0
├─ ansi-regex@5.0.0
├─ ansi-styles@4.3.0
├─ anymatch@3.1.2
├─ arg@4.1.3
├─ balanced-match@1.0.2
├─ binary-extensions@2.2.0
├─ boxen@4.2.0
├─ brace-expansion@1.1.11
├─ braces@3.0.2
├─ buffer-from@1.1.1
├─ cacheable-request@6.1.0
├─ camelcase@5.3.1
├─ chokidar@3.5.1
├─ ci-info@2.0.0
├─ cli-boxes@2.2.1
├─ clone-response@1.0.2
├─ color-convert@2.0.1
├─ color-name@1.1.4
├─ concat-map@0.0.1
├─ configstore@5.0.1
├─ create-require@1.1.1
├─ crypto-random-string@2.0.0
├─ decompress-response@3.3.0
├─ deep-extend@0.6.0
├─ defer-to-connect@1.1.3
├─ diff@4.0.2
├─ dot-prop@5.3.0
├─ duplexer3@0.1.4
├─ emoji-regex@8.0.0
├─ end-of-stream@1.4.4
├─ escape-goat@2.1.1
├─ fill-range@7.0.1
├─ get-stream@4.1.0
├─ glob-parent@5.1.2
├─ global-dirs@2.1.0
├─ got@9.6.0
├─ graceful-fs@4.2.6
├─ has-flag@3.0.0
├─ has-yarn@2.1.0
├─ http-cache-semantics@4.1.0
├─ ignore-by-default@1.0.1
├─ import-lazy@2.1.0
├─ imurmurhash@0.1.4
├─ ini@1.3.7
├─ is-binary-path@2.1.0
├─ is-ci@2.0.0
├─ is-extglob@2.1.1
├─ is-fullwidth-code-point@3.0.0
├─ is-glob@4.0.1
├─ is-installed-globally@0.3.2
├─ is-npm@4.0.0
├─ is-number@7.0.0
├─ is-obj@2.0.0
├─ is-path-inside@3.0.3
├─ is-yarn-global@0.3.0
├─ json-buffer@3.0.0
├─ keyv@3.1.0
├─ latest-version@5.1.0
├─ lowercase-keys@1.0.1
├─ make-dir@3.1.0
├─ make-error@1.3.6
├─ minimatch@3.0.4
├─ minimist@1.2.5
├─ nodemon@2.0.7
├─ nopt@1.0.10
├─ normalize-path@3.0.0
├─ normalize-url@4.5.0
├─ once@1.4.0
├─ p-cancelable@1.1.0
├─ package-json@6.5.0
├─ picomatch@2.2.3
├─ prepend-http@2.0.0
├─ pstree.remy@1.1.8
├─ pupa@2.1.1
├─ readdirp@3.5.0
├─ registry-auth-token@4.2.1
├─ registry-url@5.1.0
├─ responselike@1.0.2
├─ semver-diff@3.1.1
├─ semver@6.3.0
├─ signal-exit@3.0.3
├─ source-map-support@0.5.19
├─ source-map@0.6.1
├─ string-width@4.2.2
├─ strip-ansi@6.0.0
├─ strip-json-comments@2.0.1
├─ supports-color@5.5.0
├─ term-size@2.2.1
├─ to-readable-stream@1.0.0
├─ to-regex-range@5.0.1
├─ touch@3.1.0
├─ ts-node@9.1.1
├─ type-fest@0.8.1
├─ typedarray-to-buffer@3.1.5
├─ undefsafe@2.0.3
├─ unique-string@2.0.0
├─ update-notifier@4.1.3
├─ url-parse-lax@3.0.0
├─ widest-line@3.1.0
├─ wrappy@1.0.2
├─ write-file-atomic@3.0.3
└─ yn@3.1.1
Done in 10.95s.

続いて、APIをsrcディレクトリに作成するので、srcフォルダーを作成します。

$ mkdir src

続いて、srcフォルダーの配下に2つのファイルのindex.tshandlers.tsを作成します。

$ touch index.ts handlers.ts

handlers.tsに以下のソースを追加して、以下のを見ると、わかると思いますが。Babelがなくても、(import/export)でTSはモジュール が処理される。

import { Request, Response } from 'express';

interface HelloResponse {
  hello: string;
}

type HelloBuilder = (name: string) => HelloResponse;

const helloBuilder: HelloBuilder = name => ({ hello: name });

export const rootHandler = (_req: Request, res: Response) => {
  return res.send('Hello, Your API is working!!');
};

export const helloHandler = (req: Request, res: Response) => {
  const { params } = req;
  const { name = 'World' } = params;
  const response = helloBuilder(name);

  return res.json(response);
};

@types/expressをインストールしたので、expressパッケージ自体から型をインポートできます(TypeScriptは自動的にDefinitelyTypedパッケージを探していくことです)。たとえば、以下の通り、reqRequestのタイプだとわかる。

そして、params変数には自動的にParamsDictionaryのタイプが与えられることがわかる。

最後に、src/index.tsにhandlerをインポートしてサーバーを作成します。

import express from 'express';
import { rootHandler, helloHandler } from './handlers';

const app = express();
const port = process.env.PORT || '8000';

app.get('/', rootHandler);
app.get('/hello/:name', helloHandler);

app.listen(port, (err) => {
  return console.log(`Server is listening on ${port}`);
});

@types/nodeインストールしたので、fs、processなどnodeのデフォルトのモジュールで型の補完がきくようになる。たとえば、process.env.PORTは自動的にstring | undefinedのタイプにされます。

開発および本番環境でのサーバーの実行

これで、Nodeプロジェクトに必要なすべてのコードができました。サーバーを実行するために、package.jsonファイルにNPMスクリプトを追加します。

  "scripts": {
    "dev": "nodemon --watch 'src/**/*.ts' --exec 'ts-node' src/index.ts",
    "start": "node dist/index.ts",
    "build": "tsc"
  },

yarn devを実行すると、サーバーが開発用に起動し、Nodemonでファイルが変更されるたびにサーバーが自動的に再コンパイルされます。

本番用には、buildstartスクリプトを使います。yarn buildを実行すると、TypeScriptソースをdistフォルダにJavaScriptファイルにコンパイルして生成します。その後、yarn startを実行してappが実行できます。

最後はyarn dev を実行して、Browserでサービスの確認はしますね。

最後

これで、TypeScriptを使用してNodeプロジェクトを開始するためのテンプレートができました!いかがでしょうか?TypeScriptの安全性を得つつ、心地よく、Node.jsに組み込まれた標準モジュールを使用することができますので、これからTypeScript + Node.js でのアプリケーション開発を楽しみましょう!

Last modified: 2024-02-06

Author