How can I stop build ParcelJS build if TypeScript compilation fails?

Viewed 326

If I write invalid TypeScript, VSCode reports the error, but ParcelJS proceeds with the build anyway.

There's a noEmitOnError option for either command-line tsc or tsconfig.json. However, I don't have access to the command-line and the tsconfig.json change is not working.

2 Answers

In your package.json file, you can chain the execution of scripts.

So to stop ParcelJS from running if your TypeScript has errors you could have:

"scripts": {
    "build": "tsc --noEmit && parcel index.html",
}

(Note I haven't tested this but it should work assuming your source file is index.html)

The double ampersand enables sequential execution of the scripts; use of a single ampersand would cause parallel execution.

Alternatively you could use the run-s command in the npm-run-all CLI tool e.g.

"scripts": {
    "tsc": "tsc --noEmit && parcel index.html"
    "build": "parcel index.html",
    "tscThenBuild": "run-s tsc build",
}

This is useful if you want to access the scripts (i.e. for tsc and build) individually.

In parcel v2+, you can use the @parcel/validator-typescript plugin to do this (see docs). Here's how:

  1. Install it into your project by running yarn add -D @parcel/validator-typescript or npm install -D @parcel/validator-typescript.
  2. Add a .parcelrc file at the root of your project with the following contents:
    {
      "extends": "@parcel/config-default",
      "validators": {
        "*.{ts,tsx}": [
          "@parcel/validator-typescript"
        ]
      }
    }
    
  3. Make sure you have a valid tsconfig.json file at the root of your project, too (see this github issue). You can generate a starter one by running tsc --init.
Related