打字稿每类一个文件

时间:2015-05-07 06:44:09

标签: file class module namespaces typescript

我刚刚使用VisualScript 2015开始使用Typescript,并且无法找到在单独文件中使用类的方法。

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

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
}

1 个答案:

答案 0 :(得分:8)

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

例如:

<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

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

相关问题