Open2
TypeScript の開発環境を作る際に最初にやることメモ
package.json の作成、TypeScriptのインストール、tsconfig.jsonの作成
$ npm init -y
$ npm i -D typescript @types/node
$ mkdir src
$ touch src/index.ts
tsconfig.json の設定例
$ cat tsconfig.json
{
"compilerOptions": {
"target": "es6", // どのバージョンでjsを出力するか
"module": "commonjs", // 出力するjsのモジュールの仕組みとして何を使用するかを指定
"outDir": "dist", // 何も指定しない場合、コンパイルされたjsはコンパイルしたtsファイルと同じディレクトリに作成。このオプションでディレクトリを指定した場合、tsファイルのディレクトリ構成を保ち指定したディレクトリにjsファイルを作成
"lib": [
"es6" // コンパイルする際に使用する組み込みライブラリを指定
],
"allowJs": false, // falseだと、.jsと.jsxもコンパイル対象に含まれない
"sourceMap": true, // こちらは型定義ではなく、jsのmapファイル()
"incremental": true, // このオプションをtrueにすると、以前コンパイルを実行したコードと現在のコードとの差分を検出して、必要なファイルだけをコンパイルするようになる
"strictNullChecks": true, // Nullableな値に対してオプションの呼び出しを行う記述をエラーにする
"strictFunctionTypes": true, // 関数代入時の引数の型チェックにおいて、TypeScriptのデフォルトはBivariantlyな挙動だが、このオプションをtrueにするとContravariantlyに型チェックが走るようになる
"removeComments": true,
"strict": true,
"noUnusedLocals": true, // 宣言されたが使用されていない変数が存在する場合にコンパイルエラーにする。デフォルト値はfalse。とりあえずtrueにしておけ系
"noUnusedParameters": true // 関数の作成時、定義しているのに中身のコードで使用されない場合にコンパイルエラーにする
},
"include": ["src"], // コンパイルする対象ファイル
"exclude": ["node_modules", "dist"]
}
ESLint/Prettier package をインストール
$ npm i -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin -D prettier eslint-config-prettier
$ cat .eslintrc
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"plugins": ["@typescript-eslint"],
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"rules": {
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/consistent-type-definitions": ["error", "type"]
},
"env": {
"browser": true,
"es2021": true
}
}
$ cat .prettierrc
{
"printWidth": 120,
"singleQuote": true,
"trailingComma": "none",
"tabWidth": 2,
"useTabs": false,
"semi": false,
"jsxSingleQuote": true,
"arrowParens": "avoid",
"bracketSpacing": true,
"jsxBracketSameLine": true
}
IntelliJ IDEA Ultimate を使っている場合の設定(ハマりがち)
おまけ)Jest のインストールと jest.config.js の作成
$ npm i -D jest ts-jest @types/jest
$ npx ts-jest config:init
$ cat jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
};