javascriptangulartypescriptts-nodeangular-package-format

SyntaxError: Unexpected token { when running ts-node in Angular Package Format project


I'm trying to run a typescript file with ts-node. Getting a weird error:

 import { tes } from "./tes";
       ^

SyntaxError: Unexpected token { at Module._compile (internal/modules/cjs/loader.js:720:23)

If I copy the project ts files into an empty directory and try to run the file without any configuration it works fine, so it's something in the configuration.

I also tried generating a brand new angular package format project:

ng new proj --create-application=false
cd proj
ng g library x

And if I delete all the tsconfig files associated with the project and the library, ts-node runs fine. When I leave them in I get the same error.

The tes file is inside a Angular Package Format library. This is the top level tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "csv": [
        "dist/csv/csv",
        "dist/csv"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

This is the project specific tsconfig.lib.json :

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "target": "es2015",
    "declaration": true,
    "inlineSources": true,
    "types": [],
    "lib": [
      "dom",
      "es2018"
    ]
  },
  "angularCompilerOptions": {
    "skipTemplateCodegen": true,
    "strictMetadataEmit": true,
    "enableResourceInlining": true
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}


Thoughts?


Solution

  • It looks like your tsconfig is set to output js using esnext modules, which aren't understood by node without configuration. You can either:

    1. Remove the "module": "esnext", line from your tsconfig.json
    2. Or, assuming you want to keep your config for Angular, configure your node to use the new ES module syntax e.g. by following the answer here