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導入
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 --watch
とnodemon
組み合わせてファイル編集時に再実行する仕組みを作成する。
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",
/* 中略 */
},
更新履歴
- 新規作成。