TypeScriptの開発メモ

Download Node.js®

Node.js®をダウンロードしてインストールします。

Install TypeScript

以下のコマンドを実行してTypeScriptとyarnをインストールします。

npm install -g typescript yarn

Initialize TypeScript Project

以下のコマンドを実行してTypeScriptプロジェクトを初期化します。

mkdir my-project
cd my-project
yarn init
tsc --init

ts-node@types/nodeを インストールします。devDependenciesに追加します。

yarn add --dev ts-node @types/node

tsconfig.jsonを好みで編集します。https://www.typescriptlang.org/ja/tsconfig

LinterとFormatter導入

ESLintPrettierを導入します。

yarn add --dev eslint prettier eslint-config-prettier prettier-plugin-organize-imports

.eslintrc.js.prettierrc.jsを作成します。

yarn eslint --init

.eslintrc.js

module.exports = {
  /* 中略 */
  extends: [
    /* 中略 */
    "prettier", // 追加。他の設定の上書きを行うために、必ず最後に配置する。
  ],
};

.prettierrc.js

module.exports = {
  trailingComma: "es5",
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  bracketSpacing: true,
  arrowParens: "always",
  printWidth: 120,
  endOfLine: "lf",
  plugins: ["prettier-plugin-organize-imports"],
};

package.jsonに以下のスクリプトを追加します。

"scripts": {
  "format": "prettier --write src/**/*.{js,ts,json}",
  "lint": "eslint src/**/*.ts",
  "lint:fix": "yarn run format && yarn run lint"
},

VSCodeの設定でフォーマッターをprettierに変更した後、"editor.formatOnSave": trueにするとファイル保存時にフォーマットをかけることができます。

ホットリロード

tsc --watchnodemon組み合わせてファイル編集時に再実行する仕組みを作成する。

yarn add --dev nodemon

nomemon.jsonを作成します。

{
  "watch": ["build"],
  "ext": "js",
  "ignore": [""],
  "delay": "1000",
  "exec": "node build/app.js"
}

package.jsonに以下のスクリプトを追加します。

"scripts": {
  "start": "tsc --watch & nodemon",
  /* 中略 */
},

テスト

Jestを導入します。

yarn add --dev jest ts-jest @types/jest

jest.config.jsを作成します。

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  testEnvironment: "node",
  testMatch: ["**/test/**/*.test.ts"],
  globals: {
    "ts-jest": {
      tsconfig: "tsconfig.json",
    },
  },
};

package.jsonに以下のスクリプトを追加します。

"scripts": {
  "test": "jest",
  /* 中略 */
},

更新履歴