0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

gulp-typescriptでコメントを含むtsconfigを使う方法

Last updated at Posted at 2020-07-18

gulpでtypescriptをコンパイルするプラグインgulp-typescripttsconfig.jsonを読み込むと、エラーになります

jsonは本来コメントを含むことができませんが、tsconfig.jsonは説明用にコメントを含む(ことが多い)ためです

そこで、説明用のコメントを消さなくてもgulp-typescriptでコンパイルを行う方法を調べました

※tscはコメントを含むtsconfig.jsonを扱ってもエラーにならないようにしているようです

手順

  1. コメント付きjsonをパースできるJSONCパーサ(コメント付きJSONパーサ) を読み込む
  2. パースしたオブジェクトをgulp-typescriptの引数に渡してコンパイルを行う

初期設定

  • Typescriptのインストール
$ npm install -D typescript @types/node
$ npx tsc --init
$ npm install -D gulp gulp-typescript jsonc-parser

フォルダ構成

tsフォルダにtypescriptを配置し、コンパイル結果をjsフォルダに出力します

/project
	/src
		/ts
	/dist
		/js

gulpスクリプト

gulp-typescriptは、コメントを含むtsconfig.jsonを直接読み込めないため、jsonc-parserでパースした結果(オブジェクト)を設定として引き渡すようにします

詳細はコメント参照

  • gulpfile.js
const gulp   = require("gulp");
const ts     = require("gulp-typescript");    //TypeScriptコンパイルプラグイン
const fs     = require("fs");                 //node.js標準モジュールのため、npmでインストール不要
const parser = require("jsonc-parser");       //コメント付きjson(jsonc)用パーサ

// "gulp-typescript"はコメント付きの./tsconfig.jsonを使ってコンパイルできません
// そこで"jsonc-parser"を利用してparseを行い、コンパイルオプションとして引き渡します
const fileContent = fs.readFileSync("./tsconfig.json", "utf8");  //tsconfig読み込み
const tsconfig = parser.parse(fileContent);

// コメントがないjsonであれば読み込み可能だが、コメントがついている場合エラーが発生する
// const tsconfig= require("./tsconfig.json"); 


// src/tsをコンパイル
gulp.task("compile:ts", ()=>{
    return gulp.src(["src/ts/*.ts*"])
        .pipe(ts(tsconfig.compilerOptions))     //parseしたコンパイルオプションをセット
        .js
        .pipe(gulp.dest("dist/js/"));
});

コンパイル

エラーが発生せずコンパイルに成功しました

$ npx gulp Compile:ts
[00:33:40] Using gulpfile ~\source\repos\browserifyts\gulpfile.js
[00:33:40] Starting 'compile:ts'...
[00:33:42] Finished 'compile:ts' after 2.74 s
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?