What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typescript files which establish a model for storing data and the necessary logic to interact with the Dynamics API. Despite going through the Typescript/RequireJS documentation and related Stack Overflow questions, I am struggling to correctly implement the define statement in RequireJS to enable me to utilize my model and Dynamics API logic from my JavaScript file. Am I exporting my classes from Typescript correctly? Have I defined my import in JavaScript accurately?

Model.ts

export class ExpenseTransaction extends ModelBase {

    public Field1: string;
    public Field2: number;
    .
    .
    .

    constructor() {
        super();
    }

    toJSON(): any {
        let json = {
            "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0566667660745a436c60696134456a616471642b676c6b61">[email protected]</a>": this.Connection + "(" + this.Field1 + ")",
            "ccseq_Field2": this.Field2, 
             .
             .
             .               
        };

        return json;

    }

}

WebAPI.ts

import * as Model from './Model';

export class ExpenseTransaction extends APIBase {

constructor() {
    super();
}

ConvertToEntity = (data: Array<Object>): Array<Model.ExpenseTransaction> => {
    let result: Array<Model.ExpenseTransaction> = new Array<Model.ExpenseTransaction>();
    for (let i: number = 0; i < data.length; i++) {

        let newRecord: Model.ExpenseTransaction = new Model.ExpenseTransaction();

        newRecord.Field1 = data[i]["_Field1_value"];
        newRecord.Field2 = data[i]["ccseq_Field2"];

        result[i] = newRecord;
    }
    return result;
}

Get(): Promise<{}> {
    let expenses: Array<Model.ExpenseTransaction>;
    let self = this;
    return new Promise((resolve, reject) => {
        $.ajax({
            url: this.ExpenseTransaction,
            type: "GET",
            contentType: "application/json",
            dataType: "json",
            success: (data: any): void => {resolve(self.ConvertToEntity(data.value));},
            error: (data: any) => { reject(data.status); }
        });
    });
};

Create(expense: Model.ExpenseTransaction): Promise<{}> {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: this.Connection,
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(expense.toJSON()),
            success: (data: any): void => {resolve(data.value);},
            error: (data: any) => {reject(data.status);}
        });
    });
};
}

Compiled Typescript

define("CCSEQ/Model", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });

    class ExpenseTransaction extends ModelBase {
        constructor() {
            super();
        }
        toJSON() {
            let json = {
                "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6506061600143a230c00090154250a010411044b070c0b01">[email protected]</a>": this.Connection + "(" + this.Field1 + ")",
                "ccseq_Field2": this.Field2
            };
            return json;
        }
    }
    exports.ExpenseTransaction = ExpenseTransaction;

define("CCSEQ/WebAPI", ["require", "exports", "CCSEQ/Model"], function (require, exports, Model) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });

    class ExpenseTransaction extends APIBase {
        constructor() {
            super();
            this.ConvertToEntity = (data) => {
                let result = new Array();
                for (let i = 0; i < data.length; i++) {
                    let newRecord = new Model.ExpenseTransaction();
                    newRecord.Field1 = data[i]["_Field1_value"];
                    newRecord.Field2 = data[i]["Field2"];
                    result[i] = newRecord;
                }
                return result;
            };
        }
        Get() {
            let expenses;
            let self = this;
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: this.ExpenseTransaction,
                    type: "GET",
                    contentType: "application/json",
                    dataType: "json",
                    success: (data) => { resolve(self.ConvertToEntity(data.value)); },
                    error: (data) => { reject(data.status); }
                });
            });
        }
        ;
        Create(expense) {
            return new Promise((resolve, reject) => {
                $.ajax({
                    url: this.Connection,
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: JSON.stringify(expense.toJSON()),
                    success: (data) => { resolve(data.value); },
                    error: (data) => { reject(data.status); }
                });
            });
        }
        ;
    }
    exports.ExpenseTransaction = ExpenseTransaction;

JavaScript.js

    requirejs.config({
    bundles: {
        '../CCSEQ.Library': ['CCSEQ/Model']
    }
})

define(["require", "../jquery-3.1.1", "../papaparse.min", "CCSEQ/Model"], function (require, jquery, Papa, Model) {
    "use strict"; 
    $(document).ready(() => {
        //$("#loading").hide();
        setupHandlers();
    });
    function setupHandlers() {
        "use strict";
        $("#csv-file").change((e) => {
            //$("#loading").show();
            let file = e.target.files[0];
            if (!file) {
                return;
            }
            Papa.parse(file, {
                complete: (results) => {
                    ImportExpenseTransaction(results.data);
                }
            });
        });
    }
    function ImportExpenseTransaction(data) {
        let importData = new Array();
        data.forEach((expense) => {
            let newRecord = new Library.Model.ExpenseTransaction();
            newRecord.Field1 = expense["Field1"];
            newRecord.Field2 = expense["Field1"];
            importData.push(newRecord);
        });
        let expenseTransactionAPI = new ExpenseTransaction();
        expenseTransactionAPI.Create(importData[0]).then(() => { console.log("success"); }).catch(() => { console.log("failure"); });
    }
});

Answer №1

It seems like you haven't defined a module for ../CCSEQ.Library, but it appears that the file name you've chosen contains only CCSEQ/Model and CCSEQ/WebAPI

In AMD, usually there is one module per file, but you can configure it to map multiple modules to a single file using additional configuration (http://requirejs.org/docs/api.html#config-bundles)

requirejs.config({
  bundles: {
    'js/CCSEQ.Library': ['CCSEQ/Model', 'CCSEQ/WebAPI']
  }
})

Here, js/CCSEQ.Library is the path to a js file relative to the baseUrl (assuming your compiled TS is at /js/CCSEQ.Library.js - replace with your actual path, minus the .js extension)

Then, you would directly require the modules themselves, which will use the lookup to load the correct parent file

require(["../jquery-3.1.1", "../papaparse.min", "CCSEQ/Model",  "CCSEQ/WebAPI"], (jquery, Papa, Model, WebAPI) {
  const myModel = new Model.ExpenseTransaction()
  const myAPI = new WebAPI. ExpenseTransaction()
})

Alternatively, if you want to access them through a single Library module, you'll need to add another typescript module to export them...

Library.ts

import * as Model from './Model'
import * as WebAPI from './WebAPI'
export default { Model, WebAPI }

This will create a module CCSEQ/Library. If you compile your TS to CCSEQ/Library.js relative to the RequireJS baseUrl, you should be able to use it directly without additional configuration. Otherwise, use the mapping config as mentioned above

requirejs.config({
  bundles: {
    'js/CCSEQ.Library': ['CCSEQ/Library']
  }
})

require(["../jquery-3.1.1", "../papaparse.min", "CCSEQ/Library"], (jquery, Papa, Library) {
  const myModel = new Library.Model.ExpenseTransaction()
  const myAPI = new Library.WebAPI.ExpenseTransaction()
})

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 maintain the index of a for loop when incorporating AJAX to insert PHP data into an object?

Hey there, I'm diving into the world of AJAX and PHP implementation. I've hit a bit of a roadblock lately as I feel like I might be missing a simple solution. Currently, my code fetches data from a trove API using PHP, and for each item it appen ...

AngularJS and Gulp: Enhancing Static Assets with Revisioning

I have implemented the gulp-rev module to re-vision static assets in my source files. It generates new file names for CSS, JS, and HTML files by appending a hash code to it. Before : app.js After : app-2cba45c.js The issue I am facing is that in my An ...

Utilizing Mootools to Access and Obtain the Current Query String Parameters

Is there a way to extract the current querystring values using mootools? I have implemented mootools ajax for php pagination. The initial call includes the following parameters: format=html&nolayout=true&p[0]=1000-1500&p[1]=1500-2000&p[2] ...

Add multiple checkboxes in a dropdown menu to save in a MySQL database

I have a register.php and I'm trying to insert the data into users table. The problem I have is with "languages" field - I've created a dropdown list with multiple checkboxs. I want the user of course to be able to insert to his profile more tha ...

react tried to recycle markup error

Working on server-side rendering with React, encountering an error mentioned below. Here is the context: I have 2 React components, each stored in its own separate folder: - react-components - component-1-folder - component-1 - component-2-fo ...

Angular 12's BehaviorSubject should have been empty object array, but it unexpectedly returns undefined

Exploring different scenarios with a livesearch functionality: No user input (observable = undefined) No results found (observable = empty array) Results found (observable = non-empty array) The issue lies in how my behavior subject interprets an empty a ...

"Enable the Angular Material checkbox with the value set to checked

Check out my TypeScript code below: import {Component} from '@angular/core'; @Component({ selector: 'checkbox-configuration-example', templateUrl: 'checkbox-configuration-example.html', styleUrls: ['checkbox-config ...

Error in the Syntax of Project Image Slider

I'm encountering an issue with a WordPress script called Project Slides. Initially, this script was working fine but suddenly stopped. After investigating in the console, I found the following error: VM138 plupload-image.js?ver=4.2.2:67 Uncaught Err ...

Exploring the depths of npm in the realm of frontend development

Currently, I am delving into the realm of Javascript/Node development through self-teaching. While I grasp the concept of npm handling package installations for my Node application on the server side, I am struggling to comprehend how npm assists me with ...

Is there a way to showcase the JSON data within a nested array using VueJS?

Here is my Vue.js code: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id = window.location.href.split('=').pop(); ...

One function is failing to execute properly due to multiple if conditions

Take a look at my JavaScript code below: function showLater1() { if ((vidos.currentTime >= 30) && (vidos.currentTime <= 34)) { lay.style.opacity = "1"; content.style.opacity = "0"; controls.style.opacity = "0"; ...

Exploring Material UI: Customizing the styling of components within TablePagination

Is it possible to customize the styling of buttons within the actions panel of the TablePagination component? import { withStyles } from '@material-ui/core'; import MuiTablePagination from '@material-ui/core/TablePagination'; const st ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

Encountering an error while trying to add text: SyntaxError - Unexpected token 'for

I'm trying to print out the elements of an array using JavaScript. let listToArray = ["a","b","c"]; $(".tooltip").append(for(let i = 0; i < listToArray.length; i++) {listToArray[i]}); But I keep getting an error that says Uncaught SyntaxError: U ...

Ionic2: expanding menu options in the sidemenu

I'm not very familiar with ionic, but I have a question on behalf of my friend who is hesitant to ask on StackOverflow because she's unsure of how to frame her question. She simply wants to learn how to implement a submenu in an ionic 2 side men ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

Create a unique V-MODEL for each index that I generate

How can I customize the V-MODEL for each object generated? I am developing a cupcake website where users can create multiple forms with just one submission. However, when generating two fields, the inputs of the second field are linked to the inputs of t ...

Is there a way to automatically remove files from the "dist" directory when deleting the prototype from the "src" folder?

I am new to build systems and seeking assistance with the following question. Here is the structure of my boilerplate: /src (working folder) ___/templates(jade files) ___/scss ___/scripts /dist (compiled files) ___/css ___/js ___.html files In the te ...

Show PDF within the browser using ajax technology

I've come across this question multiple times in various forms, but I still can't seem to find a satisfactory answer. When using the mpdf library to generate PDFs, I send some hidden field data to a PHP script via ajax. Below are snippets of the ...

The error message "Potree-Core: THREE is undefined" indicates that the

I'm currently developing a web-based application that can be used offline by other users on their local machines. Within my NPM project, I am utilizing Potree-Core, which relies on THREE.js. However, the source code does not include an import for THR ...