Zenn
Open9

TypeScript Tips

ピン留めされたアイテム
takeITeasy7takeITeasy7

プロジェクト作成

  • npm init
  • npm install -D typescriptnpx tsc -v でver確認
  • npx tsc --init
takeITeasy7takeITeasy7

ローカルインストールしたtypescriptと、グローバルインストールしたtypescriptの切り替え

npxをつけるかつけないかで切り替えられる。

グローバルインストール: tsc --version  → 例. Version 5.5.4
ローカルインストール: npx tsc --version → 例. Version 5.8.2

※グローバルインストール: npm install -g typescriptでインストール
 ローカルインストール: npm install typescriptnpm install -D typescriptでインストール(package.jsonに記載された方)

takeITeasy7takeITeasy7

tsconfigの参考

以下を参考に組み合わせて作ってみる。

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.

TSConfig Reference #module

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
}
takeITeasy7takeITeasy7

ESLintの導入

npm install --save-dev eslint @eslint/js typescript typescript-eslint
ESLintはv9.0から設定ファイルのシステムが変わっているみたい。
以下の公式ドキュメントに従って導入。

作った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

takeITeasy7takeITeasy7

prettierの導入

npm install --save-dev prettier

作った.prettierrc.json
{
    "trailingComma": "es5",
    "tabWidth": 2,
    "singleQuote": true,
    "printWidth": 120
}
takeITeasy7takeITeasy7

ESLintトラブルシューティング

VSCode上で身に覚えのない(エラー内容見ても明らかにあてはまらない)エラーが表示されたら。

ESLintサーバーを再起動する。
Ctrl + Shift + P > Restart ESLint Server

takeITeasy7takeITeasy7

Jestの導入

インストール

以下に従ってインストール。
npm install --save-dev @types/jest jest ts-jest

設定ファイル(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"
takeITeasy7takeITeasy7

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"
}
}

ログインするとコメントできます