Reference a class' static field of the same internal module but in a different file?

123 views Asked by At

I'm using TypeScript and require.js to resolve dependencies in my files. I'm in a situation where I want to reference a static field of a class in an other file, but in the same internal module (same folder) and I am not able to access it, even if the Visual Studio pre-compiler does not show any error in my code. I have the following situation :

Game.ts

class Game {
    // ...
    static width: number = 1920;
    // ...
}
export = Game;

Launcher.ts

/// <reference path='lib/require.d.ts'/>
import Game = require("Game");

var width: number = Game.width;
console.log(width); // Hoping to see "1920"

And the TypeScript compiler is ok with all of this. However, I keep getting "undefined" at execution when running the compiled Launcher.ts. It's the only reference problem I'm having in my project, so I guess the rest is configured correctly.

I hope I provided all necessary information, if you need more, please ask

Any help is appreciated, thanks !

2

There are 2 answers

3
Fenton On BEST ANSWER

Your code seems sound, so check the following...

You are referencing require.js in a script tag on your page, pointing at Launcher (assuming Launcher.ts is in the root directory - adjust as needed:

<script src="Scripts/require.js" data-main="Launcher"></script>

Remove the reference comment from Launcher.ts:

import Game = require("Game");

var width: number = Game.width;
console.log(width); // Hoping to see "1920" 

Check that you are compiling using --module amd to ensure it generates the correct module-loading code (your JavaScript output will look like this...)

define(["require", "exports", "Game"], function (require, exports, Game) {
    var width = Game.width;
    console.log(width); // Hoping to see "1920" 
});

If you are using Visual Studio, you can set this in Project > Properties > TypeScript Build > Module Kind (AMD)

6
donnut On

If you are using require.js to load the (external) modules, the Game class must be exported:

export class Game {}

If you import Game in Launcher.ts like

import MyGame = require('Game')

the class can be referenced with MyGame.Game and the static variable with MyGame.Game.width

You should compile the ts files with tsc using option --module amd or the equivalent option in Visual Studio