はじめに
ReactやろうとしてもTypeScriptの話が出るのでこれは逃げられないなと悟ったのでちゃんと覚えようと思ったので今回は
こちらがTLで紹介されていたのをきっかけに入門してみようかと思いました。
いつも適当にググってモノつくり始めながらやるせいか環境設定とかが疎かになりがちなので今回はちゃんとVSCodeのデバックが動くように設定までしてみます。
環境の準備
やることは以下の3つ。
- Node.jsのインストール
- TypeScriptのインストール
- tsconfigの作成とそれに合わせてのVScodeの環境設定
Node.jsのインストール
私はnvmを使ってるので
nvm install LTEの最新版のバージョン
でインストールしました。
あとは
nvm use 使いたいバージョン
でバージョンを切り替える。
ちなみに
$ nvm list
* 14.17.4 (Currently using 64-bit executable)
14.5.0
12.18.3
こうやって確認することもできる。
TypeScriptのインストール
これは普通に
npm install -g typescript
これで解決、まあグローバルに入れておいても問題ないでしょう。
tsconfigの作成とそれに合わせてのVScodeの環境設定
まずpackage.json
を作る。
npm init -y
で、これを作成したディレクトリと同じディレクトリにtsconfig.json
を作成する。
tsc --init
作ったファイルがこれ。
ざっくりいうとTypeScriptファイルをJavascriptにコンパイルするときのオプションあれこれを指定するためのもので、これがあるディレクトリがTypeScriptプロジェクトのルートディレクトリということになるらしい。
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "esnext", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": [
"es2020",
"dom"
], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./outDir/", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
私はこのあとReactに進みたいのでとりあえずサバイバルTypeScript中で紹介されていたフロント向けの設定にしてみました。
ファイル中に英語で補足があるので各プロパティの役割はざっくりとはわかりますが、
-
target…… JSのどのバージョンに合わせてコンパイルするかの指定。これに設定したバージョンより新しい記法を使った場合、設定したバージョンに合わせたコンパイルが行われるらしい。Babelを使う場合はesnextを指定するのが無難とのこと。
-
lib…… targetで指定したバージョンにない機能や記法を使いたい場合はここで指定する。指定する場合は、targetで指定したバージョンをここでも必ず指定してから使いたいライブラリを指定する
-
sourceMap…… これをアクティブにしてTrueを設定しないとブレークポイントが機能しない
-
outDir…… コンパイルしたjsファイルをどこに出力するかの指定。ちなみに、sourceMapをtrueにすると.mapファイルも一緒にここに出力される
この辺は最低限覚えておかないといけないなと思いました。
なおjsxファイルを扱うにはもうちょっと書き込まないといけない模様、今後の課題になりそうです。
次にVSCode側の設定です。
ターミナル → 既定のビルドタスクの構成 → tsc:ビルド - tsconfig.jsonと進んでいくとtasks.json
ファイルが作成される。
以下のようなファイルができるので適宜編集する。
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
// 設定しておく、値は任意
"label": "build-ts",
"type": "typescript",
// tsconfigがある場所
"tsconfig": "test/tsconfig.json",
"problemMatcher": [
"$tsc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
次にlaunch.json
を作成する。
デバック → 構成追加 → Node.jsから作成される。
{
// IntelliSense を使用して利用可能な属性を学べます。
// 既存の属性の説明をホバーして表示します。
// 詳細情報は次を確認してください: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
// デバックの起動名
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
// 現在開いているファイルをデバックする
"program": "${file}",
// マップファイル対象外のコードのステップを省略します
"smartStep": true,
// 出力先。ここは必ず正確にパスを指定すること。
"outFiles": [
"${workspaceFolder}/test/outDir/**/*.js"
],
// task.jsのLabelに合わせる。tsconfing.jsonを使ったBuildを行うための設定
"preLaunchTask": "build-ts"
}
]
}
typeプロパティは以前は"type": "node"
だったが今はレガシーとのこと。
要はVSCodeのデバック機能でどういう動作をするかということを書く。
このファイルだと現在開いているファイルをoutDirというフォルダにコンパイルしてビルドするという動作を行う。
preLaunchTaskプロパティはtasks.json
のlabelプロパティの値を指定しておく。
で、ここまでやってうまくいけばいいのだけども、WindowsのVSCodeだとバグというか仕様というかでtasks.json
のtsconfig.json
へのファイルパスを参照する際何故か「/」抜きで参照してしまってThe specified path does not exist
とエラーを吐かれて沼ります(1敗)
なので
こちらのStackOverflowを参考に、VScodeのsetting.jsonファイルの該当プロパティを以下のようにする。
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\cmd.exe"
bashのターミナル使っててもコマンドラインでタスクは実行してくれよというオプションらしい。
こうするとちゃんと参照してくれる。
あとは、
let reaction1 : string = "Good Job!";
console.log(reaction1);
let reaction2 : string = "Never GiveUp!";
console.log(reaction2);
と試しにファイルを用意して、F5をやるとブレークポイントを指定しておけばそこで止まるので適宜続行か中止か選んだりもできる。
ここまでで問題なければデバックコンソールで以下のように結果が表示される。
改めて沼ったところ
The specified path does not exist
って言われてtsconfig.jsonを参照してくれん!
→
こちらのStackOverflowを参考に、VScodeのsetting.jsonファイルの該当プロパティを以下のようにする、ない場合は新しく追加する。
"terminal.integrated.automationShell.windows": "C:\\Windows\\System32\\cmd.exe"
デバック開始しても何故かenrichCJSError
とかミスタイプとかないのに'Unexpected token ':''
とかデバックコンソールでUncaught デバックしたいファイルのパス
と表示されてうまくデバックができない!
ググっても全然見つからないので数時間沼りましたが、こちらのStackOverflowを参考に解決しました。
ざっくり言うと
-
tsconfig.json
のmoduleプロパティの値をcommonjsにする -
launch.json
のoutFilesプロパティでちゃんと正確にパス指定されているか確認する
この2点が疑うべきポイントです。
私は前者は別にcommonjsじゃなくても問題なかったのですが、いつのまにかlaunch.json
のoutFilesプロパティが変わっていて間違ったファイルパスを指定してしまっていたので修正したら無事問題なくデバックできるようになりました。
最後に
TypeScriptのVScodeでの環境設定はなぜか色んな情報が錯綜しているのでファイルの書き方がどれも微妙に異なっていたりと大変ですが、やること自体は変わらないので新しい情報を見つけてやるのが一番良いと思いました。
基本的にはVScode側の設定はVScodeが作ってくれたものを弄らず、プロパティを足すこととパスの指定をするくらいが1番沼らないと思います。
参考
Visual Studio Code で TypeScript 環境を設定してデバッグ実行する
VSCode で TypeScript のデバック設定
VSCodeのデバッグ機能でJavascriptとTypescriptをデバッグする
Debugging TypeScript