Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript, SyntaxError: Unexpected token {

I am trying to run my program using "node main.js", however, it keeps coming up with the error "SyntaxError: Unexpected token {"

D:\Visual Studio Code Projects\ts-hello>node main.js
D:\Visual Studio Code Projects\ts-hello\main.js:1
import { LikeComponent } from './like.component';
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

I have tried changing the tsconfig.json file to "module": "commonjs", however, this did not work. I have even uninstalled and reinstalled node and started from scratch.

import{LikeComponent} from './like.component';

let component = new LikeComponent(10, true);
component.onClick();
console.log(`likesCount: ${component.likesCount}, isSelected: ${component.isSelected}`);

It should output the program correctly onto the command prompt.

like image 570
GolfBravo Avatar asked Jun 11 '19 14:06

GolfBravo


2 Answers

Notice that your are running node main.js.

Your main.js currently has esm syntax (aka ES6 module syntax).

Assuming it is compiled from main.ts, you need to have module: commonjs in your `tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    ... // other configurations
  }
}

With that, when you compile your code by running tsc, it will create main.js with commonjs module syntax.

like image 151
unional Avatar answered Oct 13 '22 00:10

unional


If you are trying to debug a vscode project and you already have "module": "commonjs", then check your "launch.json" outFiles to make sure it aligns with where your output files actually are (typically set via outDir):

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/src/index.ts",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/build/**/*.js"], //make sure this matches!
      "sourceMaps": true
    }
  ]
}

It seems like if vscode doesn't find a matching file, it just attempts to run the ts file via node (which explains the error).

I just thrashed on this for a while, so hopefully this saves someone else some headache.

like image 28
NSjonas Avatar answered Oct 12 '22 23:10

NSjonas