我正在尝试学习 TypeScript 和 Angular,但有一个奇怪的错误一直困扰着我。
简而言之,我从模块点导入了一个名为 Point 的类。该错误表明花括号是错误的。错误指向 main.ts 中的 import 语句(第 1 行)。
此外,我在一个文件夹中有 .ts 和 .js 文件。此文件夹没有 tsconfig.json 文件。
我使用以下命令编译并运行代码:
tsc main.ts --target ES2016 && node main.js
我的目标是 ES2016 以支持 getter 和 setter 属性。
错误
main.js:1
(function (exports, require, module, __filename, __dirname) { import { Point } from './point';
SyntaxError: Unexpected token {
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
main.ts
import { Point } from './point';
let point = new Point(1);
point.draw();
let x = point.x;
console.log(x);
point.y = 500;
point.draw();
point.ts
export class Point {
constructor(private _x?: number, private _y?: number) { }
get x() {
return this._x;
}
set y(value) {
if (value < 0)
throw new Error('New X must be 0 or higher.');
this._y = value
}
draw() {
console.log('X: ' + this._x + ', Y: ' + this._y);
}
}
最佳答案
这个 tsconfig.json
选项。
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"outDir": "./dest",
"strict": true,
"esModuleInterop": true
}
}
我已经像这样
tsc --p tsconfig.json
编译,一切似乎都正常。关于angular - 导入时 typescript 语法错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51574424/