Search code examples
tsc

Typescript TSC CommandLine - Prevent TSC from watching


At first: I know the difference between tsc and tsc -w in the command line. This is not the problem, it's rather a special situation:

In the tsconfig in VS Code I enabled the watcher by setting "watch":true. This is absolutely wanted. But now the problem:

I have some scripts that should install the whole VS Code project environment (so the specific project itself) and want the project initially be compiled by tsc. But now it compiles it in watch mode, since the tsconfig says to do so. Could I make an exception here? When initially compiling in the bat file I want that tsc does not automatically set the watch option to true, but compile it while igoring if the watching option in tsconfig is on or off.

Is there a way to achieve that?

Thanks!


Solution

  • You can do better than a renaming-based solution. Right now, the problem is that when you invoke tsc, the -w (--watch) flag is overridden by compilerOptions.watch value specified in your tsconfig.json (located in the same directory as the tsc script is invoked in). We'll be using a feature introduced in TypeScript 2.1: configuration inheritance.

    Base config, tsconfig.json (one-off mode)

    Write whatever the typical behaviour should be here. This will be our base (default) tsconfig file.

    {
      "compilerOptions": {
        "watch": false,
        "module": "commonjs",
        "target": "es6",
        "sourceMap": true,
        "inlineSources": true,
        "strictNullChecks": true
      }
    }
    

    Extension config tsconfig_w.json (watch mode)

    Now we write an extension for it, wherein a single property is changes: compilerOptions.watch is overridden to true.

    {   
        "extends": "./tsconfig.json",
        "compilerOptions": {
            "watch": true
        }
    }
    

    Command-line invocation of tsc

    Before, you were invoking tsc without providing any further arguments. Now, you should specify explicitly which tsconfig it should read from.

    • One-off: tsc --project tsconfig.json (this is the default file it'll use, but let's be explicit).

    • Watch: tsc --project tsconfig_w.json

    Note: the --project flag was introduced in TypeScript 1.8.

    Optional extra for convenience: package.json

    I tend to write these as convenient scripts into my package.json:

    "scripts": {
        "lib": "./node_modules/.bin/tsc  --project tsconfig.json",
        "libw": "./node_modules/.bin/tsc --project tsconfig_w.json"
    }
    

    You would then simply run npm run lib or npm run libw depending on which script you needed.

    Note: I've specified the path to TypeScript locally rather than globally (as I haven't installed it globally).