每个 Class 打字稿一个文件

Typescript One File Per Class

我刚开始使用 Typescript,使用 Visual Studio 2015,找不到在单独的文件中使用 类 的方法。

在单个文件中,没有问题:

module someModule {
    export class TitleScreenState extends Phaser.State {
        game: Phaser.Game;
        constructor() {
            super();
        }
       //some code here
    }

    class GameRunningState extends Phaser.State {
        constructor() {
            super();
       //some code here
    }

    class SimpleGame {
        game: Phaser.Game;

         //some code here
        }

    }
}

    window.onload = () => {
        var game = new MyGame.Game();
    };

然而,当 类 被移动到它们自己的文件中时,它们没有显示错误,但在运行时我得到:

0x800a1391 - JavaScript 运行时错误:'MyGame' 未定义

// app.ts

/// <reference path='Game.ts'/>
/// <reference path='StateTitleScreen.ts'/>
/// <reference path='StateGameRunning.ts'/>


    window.onload = () => {
        var game = new MyGame.Game();
    };


//----------------------------------------
// Game.s

module MyGame {
    export class Game {
    // some code here
}
  

//-----------------------------------------
// StateTitleScreen.ts
  
module MyGame {
    export class StateTitleScreen {
    // some code here
}
  
//-----------------------------------------
// StateGameRunning.ts
  
module MyGame {
    export class StateGameRunning {
    // some code here
}

当您将代码拆分为多个文件时,您需要确保它们都在运行时加载。

例如:

<script src="Game.js"></script>
<script src="StateTitleScreen.js"></script>
<script src="StateGameRunning.js"></script>
<script src="app.js"></script>

请注意,您的 app.js 是最后一个(因为这取决于其他人并且顺序很重要)。

您也可以要求 TypeScript 为您提供一个文件,使用:

--out combined.js

然后您可以在页面上引用组合文件,而不是许多单独的文件 - 但您仍然可以通过在设计时拆分为多个文件来管理您的应用程序。