如何在我的 JavaScript 文件中引用导出的打字稿 class?

How can I reference an exported typescript class in my JavaScript file?

我有一个 JavaScript 文件要将文件上传到 Microsoft Dynamics CRM。此 JavaScript 文件通过 RequireJS 引用另一个 JavaScript 文件。它引用的 JavaScript 文件是从几个 Typescript 文件编译而来的。 Typescript 文件设置了一个模型来存储要上传的数据以及与 Dynamics API 交互的逻辑。我已经阅读了 Typescript/RequireJS 文档以及几个相关的 SO 问题,但我一直无法弄清楚如何让 RequireJS 中的 define 语句正常工作,以便我可以使用我的模型和动态 API 我的 JavaScript 文件中的逻辑。我是否正确地从 Typescript 导出了我的 类?我在 JavaScript 中正确定义了导入吗?

Model.ts

export class ExpenseTransaction extends ModelBase {

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

    constructor() {
        super();
    }

    toJSON(): any {
        let json = {
            "ccseq_Field1@odata.bind": 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);}
        });
    });
};
}

编译打字稿

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 = {
                "ccseq_Field1@odata.bind": 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"); });
    }
});

您似乎没有为 ../CCSEQ.Library 定义的模块,因为这可能是您选择的文件名,但其中唯一的 ID 是 CCSEQ/ModelCCSEQ/WebAPI

通常在 AMD 中每个文件只有一个模块,但可以使用一些额外的配置将多个模块映射到一个文件 (http://requirejs.org/docs/api.html#config-bundles)

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

其中 js/CCSEQ.Library 是相对于 baseUrl 的 js 文件的路径(我假设您编译的 TS 位于 /js/CCSEQ.Library.js - 代替您的真实路径,减去 .js扩展)

然后您将直接要求模块本身,这将使用查找来加载正确的父文件

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()
})

或者,如果您想通过单个库模块访问,则需要添加另一个打字稿模块来导出它们...

Library.ts

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

这应该创建一个模块 CCSEQ/Library 如果你要将编译后的 TS 输出到相对于 RequireJS baseUrl 的 CCSEQ/Library.js,你应该可以直接使用它而无需额外的配置,否则像以前一样进行映射配置

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()
})