TypeScript Tips
プロジェクト作成
npm init
-
npm install -D typescript
→npx tsc -v
でver確認 npx tsc --init
ローカルインストールしたtypescriptと、グローバルインストールしたtypescriptの切り替え
npxをつけるかつけないかで切り替えられる。
グローバルインストール: tsc --version
→ 例. Version 5.5.4
ローカルインストール: npx tsc --version
→ 例. Version 5.8.2
※グローバルインストール: npm install -g typescript
でインストール
ローカルインストール: npm install typescript
やnpm install -D typescript
でインストール(package.jsonに記載された方)
tsconfigの参考
以下を参考に組み合わせて作ってみる。
-
tsconfig/bases
- nodeのバージョン毎にあるので、使用するnodeのVerを参照
- サバイバルTypeScript
module/moduleResolution について
typescript公式の記載にて、最新ならnodenext
が良い旨の記載あり。
バンドルするならpreserve
またはesnext
でも。
You very likely want "nodenext" for modern Node.js projects and preserve or esnext for code that will be bundled.
baseurlは書かない
baseurlはtypescriptのコンパイラ側でエラーにはならないが、トランスパイル後のビルド物でエラーになる可能性がある。
typescriptのトランスパイル時には、import文の中のパスは変更されないため、参照が見つからなくなる。
作ったtsconfig.json
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"lib": ["es2023"],
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["dist", "node_modules"],
"compileOnSave": false
}
ESLintの導入
npm install --save-dev eslint @eslint/js typescript typescript-eslint
ESLintはv9.0から設定ファイルのシステムが変わっているみたい。
以下の公式ドキュメントに従って導入。
- https://typescript-eslint.io/getting-started/#step-1-installation
- https://typescript-eslint.io/getting-started/typed-linting/
作ったeslint.config.mjs
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.strictTypeChecked,
tseslint.configs.stylisticTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: {
allowDefaultProject: ['eslint.config.mjs'],
},
tsconfigRootDir: import.meta.dirname,
},
},
ignores: ['dist/', 'node_modules/**'],
}
);
allowDefaultProject: ['eslint.config.mjs']
は、指定しないとeslintの警告が表示される。詳しくは公式サイト参照。
VSCode拡張機能も追加: ESLint
prettierの導入
npm install --save-dev prettier
- Prettierの各種設定
- https://zenn.dev/shimakaze_soft/articles/57642e22124968#tabwidth
- VSCode拡張機能: Prettier - Code formatter
- 保存時に自動整形する場合
- 設定 >
save
で検索 >Format On Save
をOnにする。
ワークスペースの設定を変えると他のプロジェクトの挙動は変わらないのでおすすめ。
- インデントのスペースの数は二つ
https://typescript-jp.gitbook.io/deep-dive/styleguide
作った.prettierrc.json
{
"trailingComma": "es5",
"tabWidth": 2,
"singleQuote": true,
"printWidth": 120
}
ESLintトラブルシューティング
VSCode上で身に覚えのない(エラー内容見ても明らかにあてはまらない)エラーが表示されたら。
ESLintサーバーを再起動する。
Ctrl + Shift + P
> Restart ESLint Server
Jestの導入
インストール
以下に従ってインストール。
npm install --save-dev @types/jest jest ts-jest
- https://zenn.dev/aew2sbee/articles/typescript-jest-coverage
- 参考(公式): https://jestjs.io/ja/docs/getting-started
設定ファイル(jest.config.js
) 作成。
作った `jest.config.js`
/** @type {import('jest').Config} */
const config = {
verbose: true,
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
coverageProvider: 'v8',
preset: 'ts-jest',
};
export default config;
※npm init jest@latest
でjest.config.tsを作成することも可能。
tsファイルの場合、ts-nodeがないとjestが起動できない点と、tsconfig.jsonのrootDirの中に入れる必要がある(自分はrootDirを./src にしているため、src配下に入れたくなかった)ため、jsで作成した。
JestにもESLintを適用したい場合
npm install --save-dev eslint-plugin-jest
以下に従ってeslint.config.mjs
に追記。
追記後の`eslint.config.mjs`
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import jest from 'eslint-plugin-jest'; //追記
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.strictTypeChecked,
tseslint.configs.stylisticTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: {
//追記
allowDefaultProject: ['eslint.config.mjs', 'jest.config.js'],
},
tsconfigRootDir: import.meta.dirname,
},
},
ignores: ['dist/', 'node_modules/**'],
},
//以下追記
{
files: ['src/**/*.spec.{ts,js}', 'src/**/*.test.{ts,js}'],
...jest.configs['flat/recommended'],
}
);
vscode-jest
vscodeの拡張機能も追加。
保存時の自動テストをオフにしたい場合は、settings.json
に以下追記。
"jest.runMode": "on-demand"
package.jsonの例
type: “module”
を追記
package.json
{
"name": "highdividendstockmanagetool",
"version": "1.0.0",
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest"
},
"devDependencies": {
"@types/node": "^22.13.8",
"typescript": "^5.8.2"
}
}
moduleについて
ECMAScriptとCommonJSがある。歴史的経緯。
ECMAScriptに変える流れが主流。デフォルトでstrictモードなどあり。
CommonJS→ECMAScript は呼び出せないが、ECMAScript→CommonJSは呼べる。