Node.js × TypeScript 環境構築手順

プログラミング
スポンサーリンク

@kijiです。今回は、TypeScirptの環境構築、テストコードの実施までをまとめていきます。
主に、バッチやスクレイピングなどの単発なプロジェクトの環境を想定しています。

本記事の環境は以下のようになっています。

  • MacOS Big Sur 11.5.2
  • npm v6.14.14

モジュールのインストール、設定ファイルの作成

$ npm init

# TypeScriptに必要なパッケージのインストール
$ npm i typescript ts-node @types/node @types/jest

# TypeScript テスト実行に必要なパッケージのインストール
$ npm i ts-jest jest 

# ソースディレクトリの作成
$ mkdir -p src/main
$ mkdir -p src/test
$ touch src/main/index.ts
$ touch src/test/index.spec.ts

# TypeScript 設定ファイルの作成
$ npx tsc --init

# Jest設定ファイルの作成
$ npx jest --init

tsconfig.jsonの修正

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "rootDir": "./src",
    "baseUrl": "./",
    "types": ["node", "jest"],
    "sourceMap": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

jest.config.tsの修正

jest.config.ts

export default {
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
};

package.jsonの修正

package.json

{
  "name": "batch",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npx ts-node src/main/index.ts",
    "build": "npx tsc",
    "test": "npx jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.10",
    "jest": "^27.1.0",
    "ts-jest": "^27.0.5",
    "ts-node": "^10.2.1",
    "typescript": "^4.4.2"
  }
}

テストコードの作成

src/test/index.spec.ts

describe('index file test', () => {
    test('sample', () => {
        expect('').toBe(false);
    });
});

テストコードの実行

$ npm run test

ビルド実行

$ npm run build

コメント

  1. […] TypeScript 環境構築手順 […]

タイトルとURLをコピーしました