【问题标题】:Intellij Typescript error for interface: SyntaxError: Unexpected identifie接口的 Intellij Typescript 错误:SyntaxError: Unexpected identifier
【发布时间】:2020-11-13 14:50:52
【问题描述】:

我正在尝试对界面进行简单的测试。 代码如下:

interface TestInterface {
    id: number;
    text: string;
}

const testInterfaceImplementation: TestInterface = {
    id: 1,
    text: 'sample text'
};

console.log(testInterfaceImplementation.text);

当我使用 Node.js 配置运行此代码时,我收到此错误:

interface TestInterface {
          ^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789: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:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

当我在没有这个接口的情况下运行代码时,它可以正常工作:

const testInterfaceImplementation = {
    id: 1,
    text: 'sample text'
};

console.log(testInterfaceImplementation.text);

有什么问题?我也尝试将界面移动到不同的 .ts 文件,但仍然出现错误。

tsconfig.json 文件:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

run_configuration

【问题讨论】:

    标签: javascript typescript intellij-idea syntax interface


    【解决方案1】:

    您不能通过将 Typescript 代码直接传递给 Node.js 来运行它,Node.js 不提供对执行 Typescript 的本机支持。代码必须即时编译或预编译。这里有一些食谱:

    使用 ts-node 运行选定的 TypeScript 文件

    • 使用npm i ts-node 安装ts-node
    • 创建一个新的 Node.js 运行/调试配置。
    • --require ts-node/register 添加到节点参数字段。
    • JavaScript 文件 字段中添加 $FilePathRelativeToProjectRoot$
    • 保存配置。
    • 使用它来运行(或调试)当前在编辑器中打开或在 项目 视图中选择的文件。您可以使用导航栏上的图标或 Run... 操作来执行此操作。

    如果您需要向 ts-node 传递任何其他参数(例如 --project tsconfig.json),您可以将它们添加到运行/调试配置中的 应用程序参数 字段中。

    使用 TypeScript 编译应用程序并运行选定的 TypeScript 文件

    • 创建 Node.js 运行/调试配置。
    • Before Launch部分,点击Add并选择Compile TypeScript
    • 选择tsconfig.json
    • JavaScript 文件 字段中,您需要选择编译后的 .js 文件的路径。
    • 如果已编译的 JavaScript 位于其源代码旁边,请添加 $FileRelativeDir$/$FileNameWithoutExtension$.js
    • 如果文件保存在输出文件夹中(保留文件夹结构),请在模式前添加文件夹名称,例如build/$FileRelativeDir$/$FileNameWithoutExtension$.js
    • 保存配置。
    • 使用它来运行(或调试)当前在编辑器中打开或在 项目 视图中选择的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-06
      • 2021-07-22
      • 2013-02-16
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多