Typescript One file per class

I just started with Typescript using Visual Studio 2015 and can't find a way to use the classes in separate files.

No problem in one file:

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();
    };
      

Run codeHide result


However, when the classes are moved to their own files, they show no errors, but at runtime I get:

0x800a1391 - JavaScript Runtime Error: "MyGame" is undefined

// 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
}
      

Run codeHide result


+3


source to share


1 answer


When you split your code into many files, you need to make sure they are loaded at runtime.

For example:

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

      

Note that yours app.js

is the last one (because it depends on others and the order matters).



You can also ask TypeScript to provide you with a single file using:

--out combined.js

      

You can then link to the combined file on your page, rather than multiple separate files, but you can still manage your application by parsing into many files during development.

+8


source







All Articles