LoginSignup
10
11

More than 5 years have passed since last update.

tscconfigファイルを読む1 - トップレベルプロパティ

Posted at

tsconfigとはなんぞ

Typescript 2になってから、トランスパイルのための設定諸々をすべてtsconfig.jsonに設定してください、ということとなっているようです。

tsconfig.jsonの簡単作り方

幸い、イチから設定を作る必要はなくて、

tsconfig.json生成コマンド
tsc --init

を実行するとカレントにtsconfig.jsonが出来上がる模様。
勉強のために使うのであれば生成されたままのものでもいいのだけれど、使いこなそうとしたら結構な設定項目があるから、「よう分からん」になってしまいそう。
なので、それを整理してみようと思います。

まずこれを見てくれ

tsconfig.json
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    // "lib": [],                             /* 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', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "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. */
    // "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. */

    /* 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. */

    /* 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. */
  }
}

これがtsc --initを使用して生成されるtsconfig.json。設定項目がたくさん。
以下で各セクションごとのパラメータを確認してみましょう。

"compilerOptions"ってなんぞ

と、その前に。jsonのキーとなっている文字列がありますね。

tsconfig.json
{
  "compilerOptions": {
    /* Basic Options */

compolerOptionsとは一体……

The "compilerOptions" property can be omitted, in which case the compiler’s defaults are used. See our full list of supported Compiler Options.

compilerOptionsプロパティはコンパイラのデフォルト設定を使用する場合は省略可能です。サポートしているコンパイラオプションの全量はCompiler Optionsを参照してください。

なるほど、つまりはtscトランスパイラの挙動を定義するプロパティがcompilerOptionsらしい。

"compilerOptions"以外のプロパティ

compilerOptions以外のプロパティとして以下のものがあります。

"files"、"include"、"exclude"

The "files" property takes a list of relative or absolute file paths. The "include" and "exclude" properties take a list of glob-like file patterns.

filesプロパティは相対パスまたは絶対パスのリストを持ちます。includeプロパティとexcludeプロパティはglob形式のファイルパターンのリストを持ちます。

リスト形式でfilesincludeexcludeのプロパティを持つ模様。

The supported glob wildcards are:

  • * matches zero or more characters (excluding directory separators)
  • ? matches any one character (excluding directory separators)
  • **/ recursively matches any subdirectory

If a segment of a glob pattern includes only * or .*, then only files with supported extensions are included (e.g. .ts, .tsx, and .d.ts by default with .js and .jsx if allowJs is set to true).

対応するglobワイルドカードの形式は、

  • *は0文字以上の文字列(ディレクトリセパレータを除く)
  • \?は任意の1文字(ディレクトリセパレータを除く)
  • **/ は任意のサブディレクトリ全てにマッチ

もしglobのパターンが*や.\/のみである場合、サポート対象の拡張子が含まれているファイルが対象となります。
(デフォルトでは*.ts、.tsx、.d.ts。allowJsパラメータが設定されている場合は、加えて*.js、.jsx)

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 except those excluded using the "exclude" property. JS files (.js and .jsx) are also included if allowJs is set to true.

fileプロパティやincludeプロパティが設定されていない場合、トランスパイラはデフォルト値として、excludeプロパティに指定された箇所を除いたディレクトリ及びサブディレクトリにあるすべてのTypescriptファイル(.ts、.d.ts、.tsx)をインクルードします。allowJsパラメータがtrueにセットされている場合は、JSファイル(.js、.jsx)も対象に含みます。

If the "files" or "include" properties are specified, the compiler will instead include the union of the files included by those two properties. Files in the directory specified using the "outDir" compiler option are always excluded unless explicitly included via the "files" property (even when the “exclude” property is specified).

fileプロパティまたはincludeプロパティが設定されている場合、トランスパイラは2つのプロパティを組み合わせで対象ファイルをインクルードします。outDirコンパイラオプションで指定したディレクトリにあるファイルはfilesプロパティで明示的に指定されない限りは常に除外されます。

Files included using "include" can be filtered using the "exclude" property. However, files included explicitly using the "files" property are always included regardless of "exclude". The "exclude" property defaults to excluding the node_modules, bower_components, jspm_packages and <outDir> directories when not specified.

includeプロパティに含まれるファイルはexcludeプロパティを使用して除外することができます。ただし、filesプロパティで明示的に指定したファイルは必ずインクルードされ、excludeプロパティの影響を受けません。
excludeプロパティが設定されていない場合、デフォルト値としてnode_modulesbower_componentsjspm_packagesoutDirパラメータのディレクトリを除外します。

つまり、filesプロパティやincludeプロパティはトランスパイルする対象を指定するプロパティで、excludeプロパティはトランスパイルしなくてよい対象をリストアップするプロパティということ。

"exrends" - tsconfig.jsonの継承

マニュアルによると、tsconfig.jsonは継承ができるようです。

The extends is a top-level property in tsconfig.json (alongside compilerOptions, files, include, and exclude). extends’ value is a string containing a path to another configuration file to inherit from.

"extends"プロパティは"compilerOptions""files""include""exclude"と同様トップレベルプロパティです。値は継承元となるファイルへのパスの文字列です。

The configuration from the base file are loaded first, then overridden by those in the inheriting config file. If a circularity is encountered, we report an error.

元となる設定がはじめに読み込まれ、それから継承先設定が上書きされます。循環読み込みが発生した場合はエラーとなります。

ベースとなる設定をextendプロパティで読み込み、それから新しい設定でどんどん上書きを繰り返していく、といった挙動のよう。

"compileOnSave" - 特定ソフトに対するトランスパイル指示

Visual Studio 2015 with TypeScript 1.8.4 and aboveatom-typescriptプラグイン限定らしいけれど、トップレベルプロパティとして"compileOnSave"があるらしい。

Setting a top-level property compileOnSave signals to the IDE to generate all files for a given tsconfig.json upon saving.

トップレベルプロパティである"compileOnSave"の設定すると、ファイル保存時にtsconfig.jsonで指定されているファイルのトランスパイルをIDEに指示します。

Visual Studio Codeを使っている方はあまり関係なさそう。ファイル保存に連動してトランスパイルしてね、ということ。

ざっくりまとめ

tsconfig.json
{
    "extends": "継承元ファイル",
    "compileOnSave": "保存時にトランスパイルするか否か※一部ソフト向け"
    "compilerOptions":{
        "コンパイラオプション": "いろいろ"
    },
    "files":[
        "厳密トランスパイル対象ファイル指定":
            "かなり強力にファイルを指定。excludeプロパティによる制御不可"

    ],
    "include":[
        "ざっくりトランスパイル対象指定":
            "トランスパイル対象を指定できるが、excludeで除外制御可能"
    ],
    "exclude":[
        "除外対象指定":
            "include対象でトランスパイルしたくないファイル・ディレクトリを指定"

    ]
}

"compilerOptions"が必須プロパティでそれ以外は省略可能なプロパティ。

compilerOptionsの中身は次回で

tsconfig.jsonのトップレベルのプロパティについて確認できた。ただ、リファレンスの原文に訳をつけながら書いていたらえらく長くなってしまった……
なので、compilerOptionsについては記事を改めるとして、一旦はここで記事を閉めようかと。

引用元

*1 Tytpescript: tsconfig.json
tsconfig.jsonに対する公式リファレンス。英語の引用はすべてここからです。

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11