Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsc --init produces tsconfig.json which is not a 100% valid JSON document #20384

Closed
another-guy opened this issue Dec 1, 2017 · 6 comments
Closed
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@another-guy
Copy link

another-guy commented Dec 1, 2017

TypeScript Version:

$ tsc --version
Version 2.6.2

Code

tsc --init

Expected behavior:

tsconfig.json with 100% valid JSON content is generated.

Actual behavior:

tsconfig.json is generated, however it contains elements which make JSON invalid, such as // and /**/ comments.

It may be perceived as a minor issue, but not for the tools that either depend on tsc itself for tsconfig.json generation, or depend on the generated 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: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "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. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "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. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* 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. */
  }
}
@j-oliveras
Copy link
Contributor

This works as intended, Typescript can read these files.

@mhegazy mhegazy added the Working as Intended The behavior described is the intended behavior; this is not a bug label Dec 1, 2017
@mhegazy
Copy link
Contributor

mhegazy commented Dec 1, 2017

As @j-oliveras noted, the compiler/editors use the TS parser to parse the JSON file and is more permissive than the standard JSON format, e.g. trailing commas, missing quotes on property names, comments, etc..

@another-guy
Copy link
Author

another-guy commented Dec 1, 2017

@j-oliveras @mhegazy I strongly disagree with the decision to use a JSON-alike format instead of valid JSON, but that's obviously not in my control.

As long as this is the expected behavior, this Github issue is definitely a bad bug report which I will close (my apologies for the false negative).

Could any of you please provide me with directions on how I can achieve the following. I am writing a script that runs tsc --init and then attempts to use JSON.parse(tsconfigFileContent) in order to replace certain parts of the configurations, and writes that back to the file. My script is supposed to only update a few specific sections of the config, and keep the rest of the file intact (including the comments that I don't like). I definitely want the script to parse the JSON into a JS/TS object rather than try to use the naive textual search/replace technique (which is pretty much "string-based programming").

Thanks

@mhegazy
Copy link
Contributor

mhegazy commented Dec 1, 2017

I strongly disagree with the decision to use a JSON-alike format instead of valid JSON, but that's obviously not in my control.

we were of the same mind for a long time. then we saw the value comments, being tolerant with trailing commas, etc, provides to users, so we become more pragmatic on this topic.

Could any of you please provide me with directions on how I can achieve the following.

You can ether use the TS API to parse the file, it parses the file as a JS object literal. see ts.parseJsonText to get an AST (JSONSourceFile object) and then ts.parseJsonSourceFileConfigFileContent to get the actual configurations (CompilerOptions object).
Or which is esier, just use the defaults as is https://github.com/Microsoft/TypeScript/blob/8f1cdc9b0c649f1e4fe9d96718be93277baa2ecd/src/compiler/commandLineParser.ts#L700-L704.

@AnmAtAnm
Copy link

AnmAtAnm commented Dec 1, 2017

@mhegazy That doesn't solve re-outputting the file with the original comments intact.

@another-guy Possible easy solution: copy the generated tsconfig.json to another location and add your edits in a new tsconfig.json that extends the original:

{
  "extends": "./configs/base",
  "files": [
    "main.ts",
    "supplemental.ts"
  ]
}

More difficult: Ignore the JSON. Just treat the the file as a regular character stream. Edit however you want.

@another-guy
Copy link
Author

@AnmAtAnm your understanding of my problem definition is more precised than @mhegazy's one. I'd like to preserve the comments as long as they are generated as a part of .tsconfig. Yet, I don't work to manipulate the config as plain text file.

So, your proposal of extending the .tsconfig seems to be a reasonable work around. I'll still look into the typescript compiler's JSON parser... Thank you both

@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

4 participants