Skip to content

Commit

Permalink
Allow comments in tsconfig.json files
Browse files Browse the repository at this point in the history
Previously, if your tsconfig.json file contained a comment (allowed by the
TS compiler) the ts-import-types-cli would throw the following error:

`ts-import-types-cli --project /myproject/tsconfig.json is not a tsconfig.json file`

This is because the node `require` function can only parse valid
(commentless) JSON.

This PR swaps out the use of `require` in favor of directly reading
the file contents, stripping all comments, and only then parsing it
to confirm that it is valid JSON.

Hopefully this will save other users some confusion!
  • Loading branch information
joshuacc committed Mar 18, 2021
1 parent 8b1e038 commit 2e4dabb
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"dependencies": {
"chalk": "4.1.0",
"commander": "6.2.0",
"strip-json-comments": "^3.1.1",
"ts-morph": "9.1.0"
},
"devDependencies": {
Expand Down
4 changes: 3 additions & 1 deletion src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import chalk = require('chalk');
import program = require('commander');
import { resolve } from 'path';
import { tsImportTypes } from '.';
import stripJsonComments from 'strip-json-comments';
import fs from 'fs';

const sourcePatterns: string[] = [];

Expand All @@ -24,7 +26,7 @@ const project = program.project || './tsconfig.json';
const tsConfigFilePath = resolve(process.cwd(), project);

try {
require(tsConfigFilePath);
JSON.parse(stripJsonComments(fs.readFileSync(tsConfigFilePath, 'utf8')));
} catch (err) {
const message = `ts-import-types-cli --project ${tsConfigFilePath} is not a tsconfig.json file`;
console.error(chalk.red(message));
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ source-map@^0.6.0:
resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"
integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==

strip-json-comments@^3.1.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006"
integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==

supports-color@^7.1.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da"
Expand Down

0 comments on commit 2e4dabb

Please sign in to comment.