Utilize RequireJS to load and initiate the primary ViewModel written in TypeScrypt

Recently, I started using requireJs and I'm facing a challenge. I want to load a viewmodel from my main script, App.ts, and retrieve a new instance of my viewModel: LienPdtUfActVM.ts.

This is how my App.ts file looks like:

declare var jQuery: JQueryStatic;
declare var $test: any;

(function ($, $test) {
    if (typeof ($test.module.Livret) == 'object') {
        return;
    }

    $easily.module.Livret = {
        init: function (data) {
            var LienPdtUfAct = require(["./Livret/ViewModel/LienPdtUfActVM"]);
            ??????
        },
        destroy: function (applicationId) {
        }
    };
})(jQuery, $test);

Here's how my LienPdtUfActVM.ts file is structured :

export class LienPdtUfActVM {
    constructor() {
    }
}

I am struggling to figure out how to create a new instance of this class.

Also, here is my tsconfig.json configuration :

{
    "compilerOptions": {
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "sourceMap": true,
        "target": "es2015",
        "module": "amd"
    },
    "compileOnSave": true
}

Solution Attempt :

I attempted the following approach:

import LienPdtUfAct = require('./Livret/ViewModel/LienPdtUfActVM');
....
new LienPdtUfAct.LienPdtUfActVM();

Although TypeScript compiler did not raise any issues, upon execution, I encountered an error message stating "Uncaught Error: Mismatched anonymous define() module: function (require, exports, LienPdtUfAct) {…". It seems that the LienPdtUfActVM.js file was not loaded properly.

Answer №1

To initialize it, follow these steps:

declare var jQuery: JQueryStatic;
declare var $test: any;
var myInstance: any;

(function ($, $test) {
    if (typeof ($easily.module.Livret) == 'object') {
        return;
    }

    $easily.module.Livret = {
        init: function (data) {
            var LienPdtUfAct = require(["./Livret/ViewModel/LienPdtUfActVM"]);
            myInstance = new LienPdtUfAct.LienPdtUfAct;
        },
        destroy: function (applicationId) {
        }
    };
})(jQuery, $test);

If you're unsure of the framework being used and what additional steps may be needed to get it up and running, this code snippet demonstrates how to instantiate it.

Answer №2

Here is the code snippet that is being executed:

$test.module.Livret = {
    init: function (data) {
        require(["./Livret/ViewModel/LienPdtUfActVM"], (LienPdtUfActVM) => {
            myInstance = new LienPdtUfActVM.LienPdtUfActVM();
        });
    },
    destroy: function (applicationId) {
    }
};

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

"Exploring the array functionality of Angular's Reactive Forms

I am encountering an issue when trying to access the products array that is located within opticanOrders inside the orderForm. Despite seeing in the console that I should reference the products array like this: orderForm.controls.opticianOrders.controls.p ...

Defining a JSON file interface in Angular to populate a dropdown box with dependencies

I've embarked on an exciting project to develop a cascading dropdown box filter, and it's proving to be quite challenging. I'm taking it step by step to ensure clarity. I have obtained a JSON file containing the data required to populate de ...

Check for the presence of an event listener before adding it in Angular 5 using TypeScript

Currently, I am involved in developing a hybrid application using Angular. The form consists of components from both Angular 6 and AngularJS. This particular project is designed as a single-page application with data spread across ten different tabs. To en ...

Error message: The attempted import failed because ' is not exported from the module

I am facing an issue with resolving my problem. In a file named lama.d.ts, I have declared a class using the following code: export declare class lama { // code here } After that, I tried to import this class in another file within the same folder ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

Issue with automatically importing Meteor packages as external libraries for .ts files

Trying to transition a Node project primarily written in TypeScript to Meteor 1.4 and encountering some difficulties. I have noticed that WebStorm is supposed to automatically import meteor when the option is selected, as explained on https://www.jetbrain ...

Use an extension module in a Node.js script

I am currently working on integrating babylon.js into my Node.js Angular application. Current Integration Process 1) I have installed the babylon.js npm repository in my project's node modules using npm install --save babylonjs. The image below i ...

Can you explain the concept of `export as namespace` in a TypeScript definition file?

While browsing through some declaration files on DefinitelyTyped, I have noticed the following pattern: declare function domready(callback: () => any) : void; export = domready; export as namespace domready; I am familiar with the first two lines - d ...

Utilizing generics with Swagger in NestJS

export class PaginatedResult<T> { @Expose() @ApiResponseProperty(type: T}) // It's unfortunate that this isn't working because it's a type but being used as a value @Transform(({ obj }) => obj.data.map((data) => new obj.cla ...

Exploring the implementation of method decorators that instantiate objects within Typescript

Currently, I have been working on a lambda project and utilizing the lambda-api package for development. As part of this process, I have implemented decorators named Get and Post to facilitate mapping routes within the lambda api object. These decorators e ...

Weird behavior observed with NativeScript Firebase and ES6 promises

My goal is to connect 2 Firebase queries using promises, as I require the result of the first query in order to execute the second one. Below are the details of the 2 queries: QUERY FOR VALUE A: private getValueA(){ var queryEvent = (result):void ...

Testing the Integration of Angular with Jasmine, utilizing a service that makes real HTTP requests

[Angular version: 2.4.5] As I dive into writing a unit test for an Angular integration component that involves a service using the Angular HTTP library, I'm encountering a challenge with the instantiation of my Service class. Either the Service ends ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...

Transferring data from a child component to a parent component in Vue without the need for a click

In my Vue project, I have a parent component called ChangeInfo which contains a child component named ShowWorkInfo. The ShowWorkInfo component includes several input forms for updating job information. To manage the data input, I created an object variable ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Accessing a variable from different tabs in an Ionic 3 weather application

I am currently exploring the world of app development and have decided to create a weather application. The main goal of this app is to display the current weather using data from the openweathermap.org API. To achieve this, I have divided my app into 3 ta ...

LoadingService is not provided in Angular 2

I've been searching for solutions to a similar issue on StackOverflow, but unfortunately, none of them are resolving my specific situation. I am currently using the latest version of Angular. Implementing Loader Component import {Component, Element ...

MasterNG - Submitting form details and uploading files with a button press

Our Angular project involves a form with various form fields along with PrimeNG FileUpload, and our goal is to send the form data along with the selected files in one go. Despite researching the documentation and numerous examples online, we couldn't ...

Encountering a 404 error when trying to retrieve the Next.js 14 API route, despite specifying the use of route

Currently, I am working with Next.js version 14.2.3 and attempting to access the /api/tmp API route from the chat.tsx component. However, I keep encountering a 404 error even though I am using the route.ts file. What could be causing this issue? UPDATE: C ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...