Understanding how to integrate compiled Typescript AMD modules into the Magento2 platform

I have been working on integrating Typescript support into Magento 2 to modernize it. Everything seems to compile correctly, but I am facing an issue with loading it.

My require-config.js file looks like this:

var config = {
    deps: [
        "web/js/app"
    ],
    bundles: {
        "web/js/app": [ "main", "moduleone", "moduletwo" ]
    }
};

In my web/js/app.js file, I have the following Typescript code:

define("moduleone", ["require", "exports"], function (require, exports) {
    // Code for ModuleOne
});
define("moduletwo", ["require", "exports"], function (require, exports) {
    // Code for ModuleTwo
});
define("main", ["require", "exports", "moduleone", "moduletwo"], function (require, exports, Module1, Module2) {
    // Main class code
});

When trying to load the module using the following script:

<script type="text/javascript">
require(['main'], function(Main) {
    console.log(Main);
    var app = new Main();
    app.start();
});</script>

I encounter the error message:

Uncaught TypeError: Main is not a constructor

Would appreciate some assistance with this issue. Thank you!

Answer №1

When writing raw AMD JavaScript, simply use return Main instead of exports.Main = Main, and that should solve the issue.

It may appear to be compiled output, but you may be mistaken.

If it is compiled from TypeScript source, you can (albeit unpleasantly) use

export = class Main {};

instead of what you currently have which is

export class Main {}

Personally, I recommend using

export default class Main {};

and bootstrapping with

<script type="text/javascript">
require(['main'], function(module) {
    var Main = module.default;
    console.log(Main);
    var app = new Main();
    app.start();
});</script>

By doing so, we can progress together and eliminate the outdated practices of TypeScript + NodeJS + CJS + AMD + Interop in browsers.

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

How is it that void can be assigned undefined?

According to the documentation on typescript, it states that "the one exception being that undefined is also assignable to void". Source Strict null checking mode specifies that null and undefined values are not within the domain of every type and can o ...

JavaScript enables logging on Android Emulator

Currently, I am working with an Ionic app that is connected to SalesForce Mobile SDK. Due to the lack of support for the SDK and certain plugins in Ionic Serve, I have resorted to running the app in Android Studio using an Emulator - specifically, the Andr ...

What is the reason for receiving a JSX warning even though JSX is not being utilized in the code?

In my Vue.js component file using the Quasar framework, I have the following code block inside the <template>: <q-btn color="green" label="save & continue editing" @click="saveCase()" /> This snippet is par ...

Changing Observable to Promise in Angular 2

Q) What is the best way to convert an observable into a promise for easy handling with .then(...)? The code snippet below showcases my current method that I am looking to transform into a promise: this._APIService.getAssetTypes().subscribe( assetty ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Issue encountered when utilizing properties in a Vue.js instance with vue-class-components and TypeScript

I am looking to create a global variable for my server's URL. In my main.ts file, I added the following line: Vue.prototype.$apiUrl = "http://localhost:3000"; Then, when trying to use it in my App.vue file: console.log(this.$apiUrl) The URL is disp ...

Error: Attempting to access a property called 'sign' on an undefined value

I encountered an issue while signing my transaction where I received an error message stating sendTransaction needs signer. Even though both message (encrypted using keccak256) and signer have values, I am unsure why there is a problem when executing the w ...

Looking for a shortcut in VSCode to quickly insert imports into existing import statements or easily add imports as needed on the go?

It seems that the current extensions available on the VSCode marketplace struggle to properly add Angular imports. For example, when I try to import OnInit using the Path IntelliSense extension: export class AppComponent implements OnInit It ends up impo ...

Encountering Typescript errors while compiling an Angular module with AOT enabled

I am currently in the process of manually constructing an Angular module with Webpack, opting not to use the CLI. While a normal build is functioning without any issues, encountering errors during an AOT build! Here's how my tsconfig.aot.json file ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName export class ConversationComponent implements OnInit { private myName: string; showNames(name) { this.myName=name; } } The value is assigned using the showNames() m ...

When attempting to add mp3 files to a Vue/TypeScript application, a "Module not found" error is triggered

I am encountering an error while trying to import .mp3 files into my Vue/Typescript app. Upon running 'npm serve', I am presented with the following message: ERROR in /Users/***/***/application/src/components/Sampler.vue(80,16): 80:16 Cannot fin ...

Using webpack to generate sourcemaps for converting Typescript to Babel

Sharing code snippets from ts-loader problems may be more suitable in this context: Is there a way to transfer TypeScript sourcemaps to Babel so that the final sourcemap points to the original file rather than the compiled TypeScript one? Let's take ...

Issue with Angular 17 button click functionality not functioning as expected

Having trouble with a button that should trigger the function fun(). Here's the code snippet I'm using. In my TS file: fun(): void { this.test = 'You are my hero!'; alert('hello') } Here is the respective HTML: &l ...

Exploring the Benefits of Utilizing the tslint.json Configuration File in an Angular 6 Project

https://i.stack.imgur.com/j5TCX.png Can you explain the importance of having two tslint.json files, one inside the src folder and one inside the project folder? What sets them apart from each other? ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Stop any ongoing search requests in Angular 7 using Ng2SmartTable

My current setup involves Angular version 7.0.1 and ng2-smart-table version 1.4.0. The issue I'm facing is that each search within the table triggers a new API request to fetch data. What I actually want is for only the latest search request to be pro ...

How do I manage 'for' loops in TypeScript while using the 'import * as' syntax?

When working with TypeScript, I encountered an issue while trying to import and iterate over all modules from a file. The compiler throws an error at build time. Can anyone help me figure out the correct settings or syntax to resolve this? import * as depe ...

Creating dynamic text bubble to accommodate wrapped text in React using Material-UI (MUI)

I am currently developing a chat application using ReactJS/MUI, and I have encountered an issue with the sizing of the text bubbles. The bubble itself is implemented as a Typography component: <Typography variant="body1" sx={bubbleStyle}> ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...