tsconfig.json
TypeScript実行方法
以下の2STEPで実行される。
STEP2 hoge.js(JavaScript)実行
・Node.js環境では、JSファイルはnodeコマンドで実行できる。
・npx tsc ---.tsをしてからnode ---.jsを毎回実行するのは面倒なので、これを1コマンドにまとめたts-nodeコマンドが存在する。 tsconfig.jsonとは?
(tscコマンドが「TS→JSにコンパイルするもの」を踏まえた上で)
・TSファイルをJSファイルにコンパイルするための設定ファイル。
・tscコマンド実行時にTSコンパイラは次の順番でtsconfig.jsonを探す。
- the current directory
- the parent direcotry chain
見つかったtsconfig.json内の設定情報をもとに、TSファイルのコンパイルを実行する。
tsconfig.jsonの設定項目
include
コンパイル対象のものを定義する。
拡張子を指定しない、もしくは拡張子にアスタリスクを使用する(hoge.*)場合、デフォルトでは下記の拡張子のファイルのみが対象になる。
・.ts
・.tsx
・.d.ts
ただし、compilerOptions.allowJsがtrueの場合は、下記の拡張子も含む。
・.js
・.jsx
exclude
コンパイル対象外のものを定義する。
なので、例えば exclude に hoge.ts を指定しても、 include に含まれている piyo.ts が hoge.ts を import していれば tsc は hoge.ts を読み込みます。
下記ドキュメントをご確認ください。
excludeは指定しない場合デフォルトで以下の値を含む。
・node_modules
・bower_components
・jspm_packages
・outDirオプションで指定しているディレクトリ配下のファイル
逆に言うと、tsconfig.jsonにexcludeオプションが指定されている場合は、outDirの中身も対象になってしまう。
extends
自分で1からtsconfig.json設定するの面倒じゃない?ということで、baseとなるtsconfig.jsonがGitHubで公開されている。自分が用意したtsconfig.jsonにて、extendsプロパティを定義することで参照できる。
Node14環境でJavaScriptを実行する場合、下記のように設定できる。
code:tx
{
"extends": "@tsconfig/node14/tsconfig.json",
"compilerOptions": {
"preserveConstEnums": true
},
}
・Typescriptでは下記のようなconst enum文をサポートしているが、JavaScriptにコンパイルされると消えてしまう。
Typescript supports costant enumerables, declared through const enum.
This is usually just syntax sugar(糖衣構文) as the costant enums are inlined(1行にまとめられる) in compiled JavaScript.
code: ts
const enum Tristate {
True,
False,
Unknown
}
var something = Tristate.True;
compiles to
var something = 0;
JavaScriptにコンパイルしてもenum定義を残しておきたい場合に、tsconfig.jsonでpreserverConstEnumsをtrueに設定すると下記のようにコンパイルされる。
code: ts
var Tristate;
(function (Tristate) {
Tristate[Tristate"True" = 0] = "True"; Tristate[Tristate"False" = 1] = "False"; })(Tristate || (Tristate = {}));
var something = Tristate.True
テンプレート(フロントエンド/JavaScript)
code: ts
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"jsx": "react",
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"baseUrl": "src",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"compileOnSave": false
}
テンプレート(バックエンド/NodeJS)
code:ts
{
"compilerOptions": {
"target": "es2020",
"module": "commonjs",
"sourceMap": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"baseUrl": "src",
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"compileOnSave": false
}
Node.js(CommonJS)でESModules構文(import/export)を扱いたい場合のtsconfig.json
ExpressをTypeScriptで書きたい時に利用。以下最低限の設定。
code: ts
{
"compilerOptions": {
"baseUrl": "./server",
"module": "commonjs", // ES記法(import/export)で書いたものをTS→JS変換時にrequire構文に直してくれる!!
"esModuleInterop": true
}
}