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

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

Mongoose retrieves the entire document, rather than just a portion of it

I'm currently experiencing an issue with my mongoose query callback from MongoDB. Instead of returning just a specific portion of the document, the code I'm using is returning the entire document. I have verified that in the database, the 'p ...

Testing the speed of the client's side

In my quest to create an application that allows users to conduct a speedtest on their WiFi network, I have encountered some challenges. While standalone speedtest apps like Speedtest.net and Google exist, server-based speed test modules from NPM are not s ...

"Exploring the world of Typescript declarations and the CommonJS module

I'm encountering confusion while creating declaration files (d.ts). For instance, I have developed an NPM package called "a" with a single CommonJS module index.ts: export interface IPoint { x: number; y: number; } export default function s ...

Having issues with the script not functioning when placed in an HTML document or saved as a .js file

Even though the database insertion is working, my script doesn't seem to be functioning properly. The message "successfully inserted" appears on the saveclient.php page instead of the index.html. In my script (member_script.js), I have placed this in ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

Should property paths be shortened by utilizing new variables for better organization?

Yesterday, someone asked me why I would introduce a variable to shorten the property path. My answer was simply that it feels easier to read. Now I am curious if there are any objective reasons to choose between the two options listed below (such as memory ...

Navigating arrays containing arrays/objects and updating properties in Angular using loops

My challenge involves an array containing arrays and objects. Within a function, I am attempting to assign a value to a specific property (for example, setting 'call' of $scope.companies[0].users to the value selected in a checkbox). Despite my r ...

Maximizing the potential of $urlRouterProvider.otherwise in angular js

I am encountering an issue with redirecting to the login screen when there is no UABGlobalAdminId in my storage. I have tried using $urlRouterProvider.otherwise but it doesn't seem to be functioning properly. When I attempt to debug, the console does ...

Dividing a sentence by spaces to isolate individual words

Recently, I encountered a challenging question that has me stuck. I am working on creating an HTML text box where the submitted text is processed by a function to check for any links. If a link is detected, it should be wrapped in anchor tags to make it cl ...

Show information in a text field from JSON in SAPUI5

How can I populate a text box with data from JSON using SAPUI5? // Sample JSON data var data = { firstName: "John", lastName: "Doe", birthday: {day:01,month:05,year:1982}, address:[{city:"Heidelberg"}], enabled: true }; // Create a JS ...

Discovering the process of extracting a date from the Date Picker component and displaying it in a table using Material-UI in ReactJS

I am using the Date Picker component from Material-UI for React JS to display selected dates in a table. However, I am encountering an error when trying to show the date object in a table row. Can anyone provide guidance on how to achieve this? import ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

An object-c alternative to encodeURIComponent

Having difficulty finding information on this through a search engine. Is there a similar method in Objective-C for encoding URI components? http://www.w3schools.com/jsref/jsref_encodeuricomponent.asp This is a common task, but I am unable to locate any ...

What are the best ways to customize exported and slotted components in Svelte?

Is there a similarity between Svelte slots and vanilla-js/dom functionality (I'm having trouble with it). In html/js, I can achieve the following: <style> body {color: red;} /* style exposed part from outside */ my-element::par ...

Unable to retrieve data from file input using jQuery due to undefined property "get(0).files"

I am facing an issue with retrieving file data in jQuery AJAX call from a file input on an ASP.NET view page when clicking a button. HTML <table> <td style="text-align:left"> <input type="file" id="AttachmenteUploadFile" name="Attachme ...

Shifting the pagination outside of the slider in ReactJS and SwiperJS seems to be tricky. Despite trying to adjust the margins and padding, the pagination

I've been struggling with this issue for a while now. I need to move the pagination outside of the slider, but using padding or margin doesn't seem to work. It always remains inside the slider, and if I try to position it outside, it gets hidden. ...

What is causing my ajax request to malfunction?

I'm encountering an issue while trying to send a request using AJAX. The request is successful when I use the following webservice: https://jsonplaceholder.typicode.com/users However, when I attempt to make the same request with my own service, I fac ...