javascript - 将 RequireJS 与导出类一起使用时,函数结果未定义

标签 javascript typescript requirejs

我正在使用 Typescript、Require 和 AMD 模块。当我调用这个函数时,它返回未定义。如果我记录函数内的值,它们都会正确返回。

如果我不在导出的类中使用 require([,它将无法编译。

从 common.ts 文件导出类。

export class DateHelpers {
    CheckMaxDateRange(fromDate: string, toDate: string, numberOfDays: Number) {
        requirejs(["moment", "alertify"], function (moment, alertify) {
            moment.locale('en');
            var momToDate = moment(toDate, "MM/DD/YYYY");
            var momFromDate = moment(fromDate, "MM/DD/YYYY");

            var dateDiff = momToDate.diff(momFromDate, 'days');

            if (dateDiff < 0) {
                alertify.alert("From Date must be before To Date.");
                return false;
            }

            else if (dateDiff > numberOfDays) {
                alertify.alert("Date range cannot be greater than " + numberOfDays + " days.");
                return false;
            }

            else {
                return true;
            }
        });
    }
}

调用函数

import * as common from "../../Common/Common.js"
let dateHelpers = new common.CheckMaxDateRange();
dateHelpers.CheckMaxDateRange($('#StartDate').val(), $('#EndDate').val(), 365)

我哪里出错了?我之前使用过的所有导出函数都不需要任何依赖项。

最佳答案

不要将 require 与 ES6 模块语法一起使用。您应该导入模块的依赖项,并配置编译器/ bundler 以支持加载外部脚本(如果您想使用 require.js 库,可以通过发出 AMD 语法模块)。

此外,您不应该使用没有状态且只有一个方法的。写

import * as moment from "moment";
import * as alertify from "alertify";

export function checkMaxDateRange(fromDate: string, toDate: string, numberOfDays: Number) {
    moment.locale('en');
    var momToDate = moment(toDate, "MM/DD/YYYY");
    var momFromDate = moment(fromDate, "MM/DD/YYYY");

    var dateDiff = momToDate.diff(momFromDate, 'days');

    if (dateDiff < 0) {
        alertify.alert("From Date must be before To Date.");
        return false;
    }

    else if (dateDiff > numberOfDays) {
        alertify.alert("Date range cannot be greater than " + numberOfDays + " days.");
        return false;
    }

    else {
        return true;
    }
}

import * as common from "../../Common/Common.js";

common.checkMaxDateRange($('#StartDate').val(), $('#EndDate').val(), 365)

关于javascript - 将 RequireJS 与导出类一起使用时,函数结果未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51712729/

相关文章:

javascript - bundle.js 是如何将样式内容注入(inject)到 index.html 中的?

javascript - 正则表达式与我的示例不匹配

javascript - 无法对元素 : not a valid selector 执行匹配

typescript - 类型 'type' 中缺少属性 'AsyncThunkAction<fetchUserResponse, void, {}>',但类型 'AnyAction' 中需要属性 0x104567910

带有 ExpressJS 错误 : Cannot read property 'prototype' of undefined 的 Node.js

javascript - 这个闭包如何使 componentDidUpdate 表现得像 useEffect?

Angular Web Worker 应用程序不显示

angular - Ionic2:如何在每个 subview 中使用不同的 ionic 菜单

javascript - Backbone Marionette : Marionette. 应用程序导致 Require.js 模块加载错误, "' 错误:模块名称 'App' 尚未加载上下文:_”

javascript - 使用 requirejs 加载模块的前缀