Home > Enterprise >  Hello world typescript code gets syntaxError: Unexpected token ':' when debugging
Hello world typescript code gets syntaxError: Unexpected token ':' when debugging

Time:05-01

I created a minimum typescript project containing very simple code.

Project structure:

my-ts/
     - hello.ts
     - tsconfig.json
      

hello.ts

let message: string = "Hello world";
console.log(message);

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "out"
    }
}

On VS Code IDE, when I press F5 which starts running the code with debugger, the debugger console shows error:

Uncaught SyntaxError /Users/john/Projects/my-ts/hello.ts:1
let message: string = "Hello world";
           ^

SyntaxError: Unexpected token ':'
    at compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1031:15)
    at Module._compile (node:internal/modules/cjs/loader:1065:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:822:12)
    at executeUserEntryPoint (node:internal/modules/run_main:81:12)
    at <anonymous> (node:internal/main/run_main_module:17:47)

Why is this error? Could someone please explain the root cause?

CodePudding user response:

Node.js can't run TypeScript natively, but you're passing it TypeScript code.

You'll need some kind of build step where TypeScript (or similar) compiles the TypeScript to JavaScript and you then run that JavaScript in Node.js. One popular way to do this is ts-node:

  1. Install it via npm install --save-dev ts-node

  2. In .vscode/launch.json, add this to the configurations array:

    {
        "type": "node",
        "request": "launch",
        "name": "Launch Program",
        "runtimeArgs": [
            "-r",
            "ts-node/register"
        ],
        "args": [
            "${workspaceFolder}/hello.ts"
        ]
    }
    

Now, pressing F5 in a .ts file will tell ts-node to compile the code to JavaScript and run the result.

Alternatively, you could use Deno (from the creators of Node.js), which runs TypeScript natively.

CodePudding user response:

@T.J.Crowder's answer is right.

But for my simple project I don't need package.json as my project directory structure indicated in my post. Only one .ts file & one tsconfig.json.

So, I solved it another way, that's in tsconfig.json add "sourceMap":true, then F5 would just run the code correctly.

  • Related