【问题标题】:Typescript internal module not recognized by VS CodeVS Code 无法识别 Typescript 内部模块
【发布时间】:2016-02-25 17:42:50
【问题描述】:

我正在尝试使用内部模块将我的打字稿类分隔在单独的文件中。但是,main.ts 文件不会加载或识别子模块。

ma​​in.ts

/// <reference path="Car.ts" />
module Vehicles {
    var c = new Vehicles.Car("red");
} 

car.ts

module Vehicles {
    export class Car {
        color: string;
        constructor(color: string) {
            this.color = color;
            console.log("created a new " + color + " car");
        }
    }
}

tsconfig.json

{
    "compilerOptions": {
        "sourceMap":  true, 
        "out": "everything.js main.ts car.ts"
    }
}

更新:编辑 tsconfig 中的“out”标志以尝试将 main.ts 和 car.ts 编译为 Everything.js - 这是最后一个不起作用的部分:everything.js 是未创建。相反,VS Code 创建了一个 main.js 和一个 car.js。似乎“out”标志被忽略了。我也尝试过“outFile”,结果相同。

【问题讨论】:

  • 您的out 错误。 module前面应该只是"outFile": "main.js". Try to add export`。
  • 另外,编译器还是会创建一个“car.js”文件,这应该不是必须的吧?
  • 您的编辑可能会创建car.js,但这不是主要问题。请将生成的main.js的内容也贴出来。
  • 嘿,它现在似乎工作了!我终于可以从单独的文件中包含内部模块了。感谢所有的帮助!显然,我什至可以省略 tsconfig.json 中的“文件”选项。现在唯一的问题是 TS 文件还没有拼接成一个大的 JS 文件。
  • 是的,files 不是必需的。我不使用该选项。我们使用gulp-typescript 来编译.ts 文件,因为我们可以增量编译代码,这样会更快。

标签: json typescript


【解决方案1】:

ma​​in.ts

/// <reference path="car.ts" />
var c = new Car("red");

car.ts

class Car {
    color: string;
    constructor(color: string) {
        this.color = color;
        console.log("created a new " + color + " car");
    }
}

tsconfig.json

{
    "compilerOptions": {
        "sourceMap":  true, 
        "outFile": "main.js"
    },
    "files": [
        "main.ts",
        "car.ts"
    ]
}

tasks.json

Kokodoko:我终于找到问题了!您必须在“tasks.json”中省略“args”选项,然后参数才会出现在 tsconfig.json 被使用!我在这里找到了答案: github.com/Microsoft/typescript/wiki/tsconfig.json。它说:当 输入文件在命令行中指定,tsconfig.json 文件是 忽略


有关模块的更多信息,别忘了查看TypeScript Handbook

【讨论】:

  • 您错过了车辆模块
  • Typescript 手册从字面上说明,您可以使用 --out 标志将多个 .ts 文件连接到一个 .js 文件中。使用上述配置文件,这部分仍然无法在 VS Code 中工作。实际上,“out”标志完全被忽略了!
  • --out 标志是用于控制台的,不要指望它在tsconfig.json 中工作,有人暗示要使用outFile,你试过吗?顺便提一句。为什么不使用 Visual Studio 2015?
  • 是的,也试过outfile。令人困惑的是,微软自己的 Typescript 文档似乎不适用于他们自己的产品 VS Code ... :( 不过我喜欢 VS Code!它又快又干净。只是很难配置。VS Studio 不适用于mac。此外,我发现该工具对于这些简单的目的有些臃肿。
  • 哦,Mac,好的。但是,是的,我同意它是一个不错的小程序。根据:code.visualstudio.com/docs/languages/typescript 你可以有一个“tasks.json”文件,包含命令和参数
【解决方案2】:

要使用 VS Code 任务将多个 .ts 文件编译成一个大的 .js 文件,您需要从 tasks.json 中删除“args”并将“out”参数添加到 tsconfig.json

tasks.json

{
    "version": "0.1.0",
    "command": "tsc",
    "isShellCommand": true,
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}

tsconfig.json

{
    "compilerOptions": {
        "sourceMap":  true,
        "out": "myapp.js"
    }
}

注意: 在命令行中指定输入文件时,会忽略 tsconfig.json 文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 2021-08-26
    • 2020-09-08
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多