我正在尝试使用“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)
我曾尝试将 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}`);
它应该在命令提示符下正确输出程序。
最佳答案
请注意,您正在运行 node main.js
。
您的 main.js
当前具有 esm
语法(又名 ES6 模块语法)。
假设它是从 main.ts
编译的,你需要在你的 `tsconfig.json 中有 module: commonjs
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
... // other configurations
}
}
这样,当您通过运行 tsc
编译代码时,它将使用 commonjs 模块语法创建 main.js
。
关于javascript - typescript ,语法错误 : Unexpected token {,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56546541/