Registering modules with System.js in a typescript project involves a specific process

In my TypeScript project, I am trying to concatenate the compiled output into a single file. I am using the SystemJs module, but I am facing an issue where the output changes when I include an 'import' statement in the script files. For example, if my source file looks like this:

export class SimpleGame{
    constructor(){
        console.log('simple game');
    }
}

window.onload = function(){
    var game = new SimpleGame();
}

The output is:

var SimpleGame = (function () {
    function SimpleGame() {
        console.log('simple game');
    }
    return SimpleGame;
}());
window.onload = function () {
    var game = new SimpleGame();
};

However, if I add another file called logic.ts and include the statement:

import { Logic } from './logic';

The output changes to:

System.register("logic", [], function (exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var Logic;
    return {
        setters: [],
        execute: function () {
            Logic = (function () {
                function Logic() {
                }
                return Logic;
            }());
            exports_1("Logic", Logic);
        }
    };
});
System.register("game", [], function (exports_2, context_2) {
    "use strict";
    var __moduleName = context_2 && context_2.id;
    var SimpleGame;
    return {
        setters: [],
        execute: function () {
            SimpleGame = (function () {
                function SimpleGame() {
                    console.log('simple game');
                }
                return SimpleGame;
            }());
            window.onload = function () {
                var game = new SimpleGame();
            };
        }
    };
});
//# sourceMappingURL=game.js.map

As a result, the code window.onload will not execute. Does anyone have any suggestions on how to resolve this issue and ensure the code executes as intended?

Answer №1

Once you've imported or exported a file, it essentially transforms into a module. To execute its code, you need to direct your loader (such as system.js) to load it. You can achieve this on your webpage by using a snippet similar to the one provided below:

<script>
    document.addEventListener("DOMContentLoaded", function(event) 
    {//Starting point of the application.
        System.import('SimpleGame').catch(function(e)
        {
            console.error(e);
        });
    });
</script>

Assuming that you've correctly set up system.js using its config method, it should know where to find your SimpleGame module.

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

What is the best way to perform unit testing on an Angular component that utilizes the Router?

While working in Angular 2.0.0, I encountered an issue when unit testing a component that utilizes Router. The error 'Supplied parameters do not match any signature of call target.' keeps appearing, with Visual Studio Code highlighting the new Ro ...

Convert image file to a React TypeScript module for export

Imagine a scenario where you have a folder containing an image file and an index file serving as a public API. Is there a method to rename the image file before reexporting it? Here is the structure of the folder: └── assets/ ├── index.t ...

React is inferring the type of the 'charts' property in the object literal as 'any[]'

ide: vscode typescript: 2.7.1 react: 16.3.0-alpha.1 interface IState { numbers: number[]; } class CustomCanvas1 extends React.Component<undefined, IState> { constructor(properties: undefined) { super(properties); this.state = { ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

Running a Typescript ES6+ server-side with .NET Core and Node.js is made easy with Jering.Javascript.NodeJS. Learn how to set

I am trying to run some TypeScript code written in ES2020 on the server side. Currently, I have an ASP.NET Core application running, so my idea was to execute JavaScript via Jering.Javascript.NodeJS and Node.js. I started with a simple example. var test = ...

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

When you type a letter in the middle of a string, the cursor is automatically moved back to the end - Material UI

I designed a ChipInput feature that switches to a string when focused and transforms into a Chip component when blurred, with chips separated by commas. Everything seems to be functioning properly except for one issue I am encountering. Whenever I type in ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...

Managing conflicting versions of React in a component library created with Webpack and Storybook

My goal is to create a React component library on top of MUI using Storybook and TypeScript. Since Storybook is based on Webpack (which includes SASS files), I'm utilizing Webpack to build the bundle because TSC can't compile those files. Subsequ ...

Converting md ElementRef to HtmlElement in Angular 2+: A Step-by-Step Guide

My query is related to retrieving the favorite food input in TypeScript. The input field is defined as: <input mdInput #try placeholder="Favorite food" value="Sushi"> In my TypeScript file, I have accessed this input using: @ViewChild('try ...

What is the method for incorporating sorting into a mat-list?

I've searched for various solutions, but none seem to work with mat-list. It's crucial for me because mat-list is the only solution where drag&drop functionality works (I always face this issue with mat-table in tables and I can't find a ...

Encountering a Typescript issue when linking a class component with the reducer

Within my class component that is linked to the redux rootReducer, I am encountering a TypeScript error specifically related to the mapPropsToState section. The error message reads: Property 'unit' does not exist on type 'DefaultRootState&ap ...

Steps for Adding a JS file to Ionic 3

I'm trying to figure out how to access a variable from an external JS file that I included in the assets/data folder. Here's what I've attempted: I placed test.js in the assets/data folder. In test.js, I added a variable testvar = "hello ...

Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6. Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when ...

The property 'x' is not found on 'Reel' type in this context

Creating a custom class extending Container in PIXI.js: export class CustomContainer extends Container { constructor(width: number, height: number) { super(); var sprite: Sprite = Sprite.fromImage("assets/images/elephant.png"); ...

Include a character in a tube using Angular

Hey everyone, I have a pipe that currently returns each word with the first letter uppercase and the rest lowercase. It also removes any non-English characters from the value. I'm trying to figure out how to add the ':' character so it will ...

Encountering a problem with Typescript and eslint while utilizing styled-components and Material UI: "Warning: React does not identify the `showText` prop on a DOM element."

While using a styled component to return a material ui Fab component, an error appears in the console: React does not recognize the `showText` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as low ...

"Dealing with cross-origin resource sharing issue in a Node.js project using TypeScript with Apollo server

I am encountering issues with CORS in my application. Could it be a misconfiguration on my server side? I am attempting to create a user in my PostgreSQL database through the frontend. I have set up a tsx component that serves as a form. However, when I tr ...

Encountering an Object Type Unknown error while working with Typescript and React

I am currently working on building a chatbox in React using TypeScript and Firebase. Below is the code for my Room and Message components: function ChatRoom() { const messagesRef = firestore.collection('messages'); const query = messagesRef.o ...

Typesafe React with TypeScript: Utilizing Types for array.map() with arrow functions

Having a background in C# but being new to js/ts, I am currently delving into React and wanting to incorporate typescript into my workflow. In an attempt to do so, I am trying to add types to a demo project located here: https://github.com/bradtraversy/pro ...