TypeScript导入时的语法错误

3

我正在尝试学习TypeScript和Angular,但是一直有一个奇怪的错误困扰着我。

简而言之,我从名为point的模块中导入了一个名为Point的类。错误提示括号不正确。错误指向main.ts中的导入语句(第1行)。

此外,我将.ts和.js文件放在一个文件夹中。这个文件夹没有tsconfig.json文件。

我使用以下命令对代码进行转译和运行:

tsc main.ts --target ES2016 && node main.js

我选择支持getter和setter属性的ES2016版本。

错误

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);
    }
}

错误信息是什么?你链接的似乎是一些转译代码?最有可能的是,由于你正在使用模块,你还需要获取一个模块加载器来运行代码,否则无法运行。 - toskv
在控制台中,也有一个箭头指向 import { Point 中的 {。 - Tim
@CristianTraìna 我怎么才能找到这个?我基本上使用编译器而不修改配置。 - Tim
@toskv,实际上我没有tsconfig.json文件...只有该文件夹中的main.ts、main.js、point.ts和point.js。 - Tim
1
@Tim 这与 Node 版本有关,你必须使用 --harmony 标志来运行。 - Muhammed Albarmavi
显示剩余7条评论
1个回答

3

这是有关 tsconfig.json 选项的内容。

{
   "compilerOptions": {
    "target": "ES2016",
    "module": "commonjs",
    "outDir": "./dest",
    "strict": true,
    "esModuleInterop": true
  }
}

我已经按照如下方式进行编译:tsc --p tsconfig.json,一切看起来都很正常。

typescript compile

typescript版本:2.9.2 node版本:v10.2.0


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接