打字稿:如何导入 类 ("Uncaught ReferenceError")

Typescript: How to import classes ("Uncaught ReferenceError")

我是 Typescript 的新手。我喜欢这个想法,编译器会指出大部分错误,因为他真的得到了代码。现在我做了一个测试项目,没有编译错误,但运行时出现异常:

Uncaught ReferenceError: Boat is not defined(anonymous function) @Main.ts:7

显然导入不起作用。但为什么?我尝试使用 amd 和 commonjs 并得到了同样的错误。

这里是代码:

index.html

<!DOCTYPE html>

<html>
<head>
    <title>TypeScript Test</title>
    <script data-main="main" type="text/javascript" src="require.js"></script>
</head>
<body>

<span id="output"></span>

</body>
</html>

Main.ts

///<reference path='Vehicle.ts'/>
///<reference path='Car.ts'/>
///<reference path='Boat.ts'/>

var outputElement = document.getElementById('output');

var vehicleOne: Vehicle.Vehicle = new Boat.Boat("One");
var car: Car.Car = new Car.Car("Two");
var vehicleTwo: Vehicle.Vehicle = car;

outputElement.innerHTML = vehicleOne.do() + " " + vehicleOne.getName() + "<br />"
                        + vehicleTwo.do() + " " + vehicleTwo.getName() + "<br />"
                        + car.do() + " " + car.getName() + " " + car.doCar() + "<br />";

Vehicle.ts

module Vehicle{

    export class Vehicle
    {
        private name: string;

        constructor (name: string)
        {
            this.name = name;
        }

        do() : string
        {
            return "Im a vehicle";
        }

        getName() : string
        {
            return this.name;
        }
    }

}

Car.ts

///<reference path='Vehicle.ts'/>

module Car {

    export class Car extends Vehicle.Vehicle {
        constructor(name:string) {
            super("CAR: " + name);
        }

        do():string {
            return "Im a car";
        }

        doCar():string {
            return "Only cars can do this :)";
        }
    }

}

Boat.ts

///<reference path='Vehicle.ts'/>

module Boat {

    export class Boat extends Vehicle.Vehicle {
        constructor(name:string) {
            super("BOAT " + name);
        }

        do():string {
            return "Im a boat";
        }
    }

}

我使用的是Webstorm,编译器没有输出任何错误,并且创建了*.js和*.map.js文件。在浏览器中没有输出。只有控制台打印“Uncaught ReferenceError: Boat is not defined(anonymous function) @ Main.ts:7”

为什么会出现这个异常?如何正确导入 类?

我怀疑您的项目设置为将每个 .ts 文件编译成一个单独的 .js 文件。如果是这种情况,则只会加载 Main.js,但不会加载 boat.js、car.js 等,给您一个错误。

如果您更改项目以将输出编译为单个文件,则 TypeScript 编译器将使用 标签引入其他 .ts 文件并构建一个您可以使用标签引用的 .js 文件.

如果您使用的是 Visual Studio,则在项目设置的 TypeScript Build 下有一个选项“将 JavaScript 输出合并到文件中”。如果您使用命令行编译器,那么 --out标志可用于生成单个文件 - 有关详细信息,请参阅 http://www.typescriptlang.org/Handbook#modules-splitting-across-files

我遇到了类似的问题,这是因为 html 文件没有导入所有 javascript 文件。要解决您的情况,您可以将 Vehicle.js、Car.js 和 Boat.js 添加到 index.html 文件中。