簡體   English   中英

Nodejs/Typescript 錯誤:SyntaxError:意外令牌:

[英]Nodejs/Typescript error: SyntaxError: Unexpected token :

我在名為 spartan.ts 的單獨文件中定義了一個類,它是這樣的:

class Spartan {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    test() {
        return this.name;
    }
}

module.exports = Spartan;

然后我將其導入其他文件,如下所示:

var Spartan = require("../entities/spartan.ts");
var mySpartan = new Spartan("myName");
console.log(mySpartan.test())

我的 tsconfing.json 看起來像這樣:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

然后我得到這個錯誤:

SyntaxError: Unexpected token :
        at createScript (vm.js:80:10)
        at Object.runInThisContext (vm.js:139:10)
        at Module._compile (module.js:616:28)
        at Object.Module._extensions..js (module.js:663:10)
        at Module.load (module.js:565:32)
        at tryModuleLoad (module.js:505:12)
        at Function.Module._load (module.js:497:3)
        at Module.require (module.js:596:17)
        at require (internal/module.js:11:18)
        at Object.<anonymous> (/U.../routeRepository.ts:2:15)

您可能應該使用 ES2015 模塊語法進行導入/導出,例如:

export class Spartan {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    test() {
        return this.name;
    }
  }

進而:

import { Spartan } from "../entities/spartan.ts";
let mySpartan = new Spartan("myName");
console.log(mySpartan.test())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM