How to import a TypeScript class into a JavaScript file using AMD and RequireJS

Below is the TypeScript class found in the file called bar.ts

export class Bar {
   log(message:string):void {
       console.log(message);
   }
}

In a separate file named foo.ts, the following code exists:

import { Bar } from "bar";

window.onload = () => {
   var foo = new Bar();
   foo.log("Hello World");
};

During compilation, the settings are as follows:

lib: ["dom", "es2015.promise", "es2015"]
module: "amd"
declarationFiles: true
target: "ES5"
noImplicitAny: true
out: "test.js

What is the correct way to create an instance of the Bar class? The window.onload event does not seem to trigger. Here is the resulting JavaScript code:

define("bar", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Bar = (function () {
        function Bar() {
        }
        Bar.prototype.log = function (message) {
            console.log(message);
        };
        return Bar;
    }());
    exports.Bar = Bar;
});

define("foo", ["require", "exports", "bar"], function (require, exports, bar_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    window.onload = function () {
        var foo = new bar_1.Bar();
        foo.log("Hello World");
    };
});

Is there a method to access Bar from regular JavaScript? I have included require.js in the HTML page and no errors occur when loading the page.

This scenario is a simplified version, but it is necessary to use export due to multiple classes stored in individual files that need to be merged into one.

Answer №1

Accessing Bar from plain JavaScript is possible. Experiment with referencing it in the requirejs data-main script.

Within the HTML:

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

In scripts/main file:

requirejs(["bar"], function(bar) {});

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

Tips for Verifying Browser Closure Status in an Angular 4 Application

In the process of developing my Angular Application, I have successfully implemented Login and Logout functionalities. Upon clicking logout, the user's status in the Database is updated using Laravel API. However, I am facing the challenge of handling ...

What is the method for incorporating text into the Forge Viewer using three.js?

Currently, I am attempting to incorporate TextGeometry into the viewer using Three.js. I am curious about the feasibility of this task and the steps to achieve it. After exploring the documentation, I encountered challenges as the Forge viewer operates on ...

Upon sending an HTTP POST request from JavaScript to a Node server, the body was found to be

Trying to make an XMLHttpRequest from JavaScript to my node server. This is the request I am sending: var data = { "fname": "Fasal", "lname": "Rahman" }; var body = JSON.stringify(data); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/admin"); xhtt ...

Vue component not displaying object property

I am currently working on implementing a filter method in a Vue component. Here is the filter method I am trying to use: filterHotels:function(){ var thisHotels = this.hotelRoomArr; console.log(this.hotelRoomArr['107572']['rooms ...

JavaScript function to handle varying screen resolutions

I'm new to JavaScript and currently working on implementing a sidebar navigation. I found a tutorial on W3Schools, but the script provided only works for full-screen desktop browsers. <script> function openNav() { document.getElementById("myS ...

JavaScript object value not accessible due to SyntaxError: Unexpected token, expected ,

While working on aliases.js, I encountered an issue when attempting to retrieve the value of the 'SELECT_HOST' property from the imported actionTypes object. This led to a "SyntaxError: Unexpected token, expected ," error according to Webpack. I& ...

Changing a date format in typescript: Here is how you can easily convert a date from one

Using React with Typescript: I am currently working with a date picker from material-ui version 5. The date picker requires the date value to be in the format "yyyy-MM-dd". However, the API returns a Date object in the format "2022-01-12T00:00:00.000+00:0 ...

Angular 4: Leveraging a directive as a universal constant

I am looking to develop a directive that allows me to utilize a template variable in order to access a global variable, much like $rootScope in Angular.JS. The goal is to avoid having to inject a service into every component where I need access to the vari ...

Here is how you can pass two callback functions to React.cloneElement:

Recently, I encountered an issue where one of the callbacks passed to a child component using React.cloneElement was always present while the other was undefined. Specifically, activeRow was consistently available but deactivateRow remained undefined. I ...

Add drop caps to every individual word within a hyperlink

Is there a way to recreate the menu effect similar to using CSS fonts and drop caps for each word? I'm aware of the CSS code: p.introduction:first-letter { font-size : 300%; } that enlarges the first character of the first word, but I want this ef ...

Adjusting diagram size based on screen width using Bootstrap and jQuery

I recently created a diagram that adjusts its size according to the screen width. However, when I implemented this code on my page, I encountered an issue where the final circle or glyph would drop to the next line instead of staying on the same line as in ...

In React conditional return, it is anticipated that there will be a property assignment

What is the optimal way to organize a conditional block that relies on the loggedIn status? I am encountering an issue with a Parsing error and unexpected token. Can someone help me identify what mistake I am making and suggest a more efficient approach? ...

Is there a way to alter a modal's content in React without having to pass all the DOM elements as props?

I'm a newcomer to React and I'm currently working on creating a Two-Factor-Authentication modal-style UI for my project. The design of the modal is relatively simple: Title A message Modal Content (which can be an input box, one or more drop-d ...

Display checkboxes on all TableRow elements as soon as one of them is checked

I've incorporated a material-ui Table into my project and have successfully implemented multi-select functionality. Here are the requirements I've fulfilled so far: Checkboxes are initially hidden - COMPLETED Hovering over a row reveals its che ...

How does NodeJs handle ongoing tasks and processes seamlessly?

One interesting concept is the Event Loop, which accepts callbacks and executes them as needed. As far as I understand, this operates on a single thread event loop, meaning only one callback is executed at a time. Consider the following example: setInterv ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...

The search for global types seems to bewilder Mocha

Recently, I developed a small node application using Express and created a global interface called "LocalUser," which is essentially an express response with predefined locals. Instead of importing it everywhere, I opted to define a global type for it. dec ...

JavaScript not displaying properly in Django application deployed on Heroku

Recently deployed a Django application on Heroku, and encountered an issue where the Javascript file hosted on Amazon S3 is not rendering on any page except for the home page. However, upon checking the Console in Inspect Element, it appears that everythin ...

Is it possible to trigger a submit button to perform a POST request and an AJAX call simultaneously

I have a form that sends a POST request to show_aht2.php, but I also need it to trigger an AJAX call as shown in the code below. How can I achieve this without redirecting the user to another page? I want the user to remain on map.php. Thank you in advanc ...

React loop-generated elements are being ignored by tab selection

In my application, I have a radio group that is generated based on the array const genders = ["Male", "Female", "Neutral"];. However, when I press the tab button, the focus only falls on the first element and skips the rest of the elements. const { useS ...