TypeScript お試し環境をお手軽コピペコマンドで

小ネタです。コピペでおk。Mac なら動くと思います。
VS CodeVS Code ESLint extension をインストールしておくと ESLint の自動修正も動くので快適です。

echo mkdir
mkdir ts-`date '+%Y%m%d%H%M%S'` && cd $_
echo typescript
npm init -y && npm i -D typescript && node_modules/.bin/tsc --init && echo -e "const arr: number[] = [1, 3, 5];\nconsole.log(arr);" > index.ts

# prettier 使いたい人はここも
echo prettier
npm i -D prettier && echo -e '{\n  "singleQuote": true,\n  "trailingComma": "es5"\n}' > .prettierrc

# さらに eslint 使いたい人はここも
echo eslint
npm i -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-prettier eslint-plugin-prettier && echo -e '{\n"root": true,\n"env": {\n"browser": true,\n"node": true\n},\n"extends": [\n"eslint:recommended",\n"plugin:@typescript-eslint/eslint-recommended",\n"plugin:@typescript-eslint/recommended",\n"plugin:prettier/recommended",\n"prettier/@typescript-eslint"\n],\n"rules": {}\n}' > .eslintrc && node_modules/.bin/prettier --write .eslintrc

# さらに vscode で eslint の auto fix 使いたい人はここも
echo vscode
mkdir .vscode ; echo -e '{\n"editor.formatOnSave": false,\n"editor.codeActionsOnSave": {\n"source.fixAll.eslint": true\n}}' > .vscode/settings.json && node_modules/.bin/prettier --write .vscode/settings.json

# git もお好みで
echo git
git init && echo node_modules/ > .gitignore && git add . && git commit -m 'init'

実行結果

.
├── .eslintrc
├── .git
├── .gitignore
├── .prettierrc
├── .vscode
│   └── settings.json
├── index.ts
├── node_modules
├── package-lock.json
├── package.json
└── tsconfig.json

何ができるの

  • typescript のインストール
  • tsc --init を利用した TypeScript プロジェクトの初期化と tsconfig.json の生成
  • ESLint と prettier のインストールと設定
    • Lint には最低限と思われる recommended な設定だけいれてあります
      eslint:recommended, plugin:@typescript-eslint/recommended
      各ルールがコンフリクトしないための設定もいれています

何に使うの

  • ローカルで手軽に TypeScript の挙動確認をするため
  • https://stackblitz.com/http://www.typescriptlang.org/play/ も便利でよく使いますが、TypeScript のコンパイラの挙動を確認したり npm install したパッケージのコードを確認したい時はローカルで動かしたほうが捗るので
  • 正直 tsc --init だけで十分です。フォーマット崩れが気になってしまう人向けです
  • すでに設定が完了している環境 (例えば開発中のアプリケーションや npx create-xxx 的なもの) を使って挙動確認していると、前提知識や設定の違いでハマったりするので気をつけましょう
  • プロダクトに使うようなものではありません

その他

  • 手軽に実行するなら node_modules/.bin/tsc
  • 出力先をかえたい
  • コンパイル対象を変更したい
    • tsconfig.jsonfiles, include, exclude を変更
    • 初期設定は If the "files" and "include" are both left unspecified, the compiler defaults to including all TypeScript (.ts, .d.ts and .tsx) files in the containing directory and subdirectories です
    • import 対象になっているファイルは、config 上で対象になっていなくてもコンパイル対象になります
  • 読み込んでいる型定義ファイルを変更したい
    • tsconfig.jsontypes, typeRoots を変更
    • 初期値は all visible “@types” packages are included in your compilation. です。node_modules/@types などが対象になっています
    • 重要なこと Keep in mind that automatic inclusion is only important if you’re using files with global declarations (as opposed to files declared as modules).