打字稿,语法错误:意外的令牌{

Gol*_*avo 5 javascript typescript ecmascript-6

我正在尝试使用“node main.js”运行我的程序,但是,它不断出现错误“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)
Run Code Online (Sandbox Code Playgroud)

我曾尝试将 tsconfig.json 文件更改为 "module": "commonjs",但是,这不起作用。我什至卸载并重新安装了节点并从头开始。

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

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

它应该将程序正确输出到命令提示符上。

uni*_*nal 7

请注意,您正在运行node main.js.

main.js当前有esm语法(又名 ES6 模块语法)。

假设它是从 编译的main.ts,你需要module: commonjs在你的 `tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "module": "commonjs",
    ... // other configurations
  }
}
Run Code Online (Sandbox Code Playgroud)

这样,当您通过运行编译代码时tsc,它将main.js使用 commonjs 模块语法创建。