When including an import statement in Typescript, 'window' events will not be triggered

As someone who primarily works on native apps, diving into the world of TypeScript, JavaScript, and web development with Phaser3 has been quite the learning experience for me. I've transitioned from using namespaces to exports and imports in my TypeScript files, but encountered an issue where my window event (window.onload) wasn't firing due to a required type being imported.

This window event serves as the entry point to my app, so not having it fire was a major roadblock. I'm open to suggestions on alternative approaches to getting my project started successfully. Here's the segment of code causing the problem:

window.onload DOES NOT FIRE:

import { Boot } from "./Boot";

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

Upon removing the 'import' statement, 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!!);
//Code to start the game... (excerpt of code)
        }
}

This is how my tsconfig looks like:

{
    "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 insights into why this behavior occurs? It's frustrating as that part launches my game logic. Would it be feasible to trigger my 'Boot.runApp()' function from a script tag in my index.html instead?

Answer №1

When you use the import/export keywords in your code, you are essentially creating a module. In the context of SystemJS (module: system specified in your tsconfig), modules are encapsulated within 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");
            };
        }
    };
});

To execute the code within this module, you need to run something like System.import('index.js');. However, if your TypeScript file is not set up as a module, the code within window.onload will be directly included in the compiled output without being wrapped in a System.register block. This means that it will be executed immediately upon loading the file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue3 and Ionic combined to create a Component that became a reactive object in Vue

Vue is issuing a warning about receiving a Component as a reactive object, which can cause unnecessary performance overhead. The warning suggests using markRaw or shallowRef instead of ref to avoid this issue. However, in my code, I am not explicitly using ...

Reopen a Kendo UI dialog

Currently, I am utilizing Kendo UI, and my goal is to display a modal dialog when a button is clicked. The issue I am facing is that it works perfectly the first time around. However, upon closing the dialog and attempting to reopen it by clicking the butt ...

What steps are involved in connecting FourSquare Venues with the Angucomplete library in Angular?

I'm endeavoring to incorporate Foursquare venues into my Angular application using the angular angucomplete. However, the datafield in angucomplete necessitates an array of objects, while the response from Foursquare is returned as an array of arrays ...

Toggle the visibility of a div depending on the user's selection

My HTML select element has a few options to choose from: <select class="form-control" data-val="true" data-val-number="The field CodeSetup must be a number." id="CodeSetup" name="CodeSetup"> <option selected="selected" value="0">AllCodes< ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

How can values be shown on the links/paths of a Sankey Graph in R programming?

Story While attempting to recreate a Sankey graph similar to the one shown in the image below, I aimed to assign specific values (10, 20, 30, 40) to the paths connecting different nodes. https://i.sstatic.net/U3erS.png My Approach Initially, I used the ...

Tips for sending asynchronous data to Google-Charts-Angular

I am currently working on generating a chart using data obtained from an API call. To achieve this, I am utilizing the google-charts-angular package within my HTML: <google-chart [title]="title" [type]="type" [data]="data" ...

Guide on streamlining interface initialization within a React project using Typescript

Working on my Typescript project, I consistently utilize an interface within the State of various components: interface Item { selectedValue: string originalSelectedValue: string loading: boolean disabled: boolean isValid?: boolean } ...

Angular: Monitoring changes in forms

Currently, I am working on developing an Angular application where I need to monitor any changes in the form and execute specific operations based on those changes. While I am aware that this can be done using $scope.watch, I am concerned about the impact ...

Why does the useEffect of other components get triggered when accessing a link for just one component?

When accessing the link localhost/profile, I noticed that two additional POST requests are being sent from the front-end to the back-end. After further investigation, it was discovered that the useEffect hooks present in Controller.js file are being execut ...

Utilizing React-Redux along with Redux-Thunk in a functional component to dynamically modify the UI upon receiving data from an external API

Within my functional component, I am utilizing a custom hook to fetch data from an API using Redux. const useFetching = (someFetchActionCreator) => { const dispatch = useDispatch(); useEffect(() => { dispatch(someFetchActionCreator() ...

Guide to constructing a multi-dimensional array using dynamically generated fields and variables

Here is the URL that I wanted to share with you: All the fields visible on this page are generated dynamically from the backend. To display the pricing, I used the field names as variables in the JavaScript below. However, I encountered two issues - first ...

Dynamically insert components into table rows with ComponentFactory in Angular version 6

My component contains the following HTML structure: <table> <thead> <tr> <th> </tr> </thead> <tbody> <ng-container #container class="sample"> </ng-container> </tbody> </table ...

JavaScript array images are not showing when using the img tag

For this module, I am working on creating a flipbook (magazine) using images stored in a JavaScript array. However, I am facing an issue where the images are not loading up properly. Instead of displaying the image, it shows as [object" htmlimageelement]=" ...

Exploring Multi-Level TileMaps in Phaser 3 with JSON

My game currently only restarts on the same tilemap, even when the key is set to level-2. I'm trying to figure out the best way to implement multiple levels. I attempted a solution where "level-2" was designated as the key, but the tilemap failed to ...

conducting a remote call via javascript

Looking for a way to achieve the same functionality as a link_to ... remote=> true using JavaScript? It may not even be necessary - Imagine having a div containing the user's name and profile picture. My goal is to have the entire div react to a ...

Ways to retrieve an isolated scope in a directive without utilizing a template

It is clear that when I assign a controller to an element, the element along with its children can access the controller's scope. However, it is surprising that when I include a directive with an isolated scope on an element (as an attribute), I woul ...

Guide on embedding a form component within an iframe using ReactJS

I am trying to figure out how to render my form component inside an iframe, but so far it's only rendering the iframe itself. Any tips on how to accomplish this task? import './App.css'; import ReactDOM from "react-dom/client" impo ...

Tips for importing queries from a .graphql file using Angular and TypeScript

I am currently developing an app using Angular and Ionic. For the backend, I have set up a node server running ApolloServer with Neo4j (utilizing grandstarter.io). On the frontend, I have a file named queries.ts where I define my graphql queries in the fol ...