gpt4 book ai didi

node.js - Nodejs/ typescript 错误: SyntaxError: Unexpected token :

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:44 24 4
gpt4 key购买 nike

我在名为 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())

关于node.js - Nodejs/ typescript 错误: SyntaxError: Unexpected token :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52385445/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com