简体   繁体   中英

Typescript, no 'window' events when adding an import statement

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM