0

So I'm pretty new to typescript, javascript and web-shizzles (I normally build native apps). But I'm experimenting with Phaser3 and use VSCode with typescript to transpile the javascript files. First I used namespaces (C# background), but apparently that's not the way to go in typescript, so I removed the namespaces and used export with corresponding import statements.

The problem: It took me a while to figure out that my window event (window.onload) doesn't fire because of importing a required type. This event is kind of the entry point to the app. Suggestions for other ways to kick start the project are always welcome. Here is the code:

window.onload DOES NOT FIRE:

import { Boot } from "./Boot";

window.onload = () => {
    console.log("Test");
    Boot.runApp();
}

After removing the 'import', window.onload FIRES!

//import { Boot } from "./Boot";

window.onload = () => {
    console.log("Test");
    //Boot.runApp();
}

Boot.ts

imports...

export class Boot {
        static runApp() {
            console.log("RUN APP!!");
//Start the game... (code removed)

        }
}

This is my tsconfig:

{
    "compileOnSave": true,
    "compilerOptions": {
        "target": "ES5",
        "module": "system",
        "sourceMap": false,
        "outDir": "bin/js/",
        "outFile": "bin/js/game.js"
    }, 

    "include": [
        "./src/**/*"
        ],

    "files":[
        "./tsDefinitions/nineslice.d.ts",
        "./tsDefinitions/phaser.d.ts"
    ]    
}

Any ideas why it behaves like this? It's a bit annoying because that spot launches my game code. Is it possible to start my 'Boot.runApp()' function from a tag in my index.html?

1
  • 1
    What is Boot and what does it do? How are you actually running this code? Basically we need a Minimal, Reproducible Example Commented Jul 10, 2019 at 8:06

1 Answer 1

1

When you import/export you create a module. You are using SystemJS (module: system in your tsconfig). Modules are wrapped in system register blocks:

System.register("index", [], function (exports_2, context_2) {
    "use strict";
    var __moduleName = context_2 && context_2.id;
    return {
        setters: [],
        execute: function () {
            window.onload = function () {
                console.log("Test");
            };
        }
    };
});

You need to run something like System.import('index.js'); to run that code. When your typescript file is not a module, the window.onload is put directly into the compiled output, not wrapped in a System.register, which means it will be immediatly executed when you load the file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.