【问题标题】:TypeScript export/import functionTypeScript 导出/导入功能
【发布时间】:2017-01-22 01:22:29
【问题描述】:

我有一个我编写的模块(通过 npm 从私人仓库安装),其结构如下:

email.ts、utils.ts、index.ts、(一些其他文件)

在我的 email.ts 上,我有以下功能:

export default function sendEmail(toEmail: string, subject: string, content: string): any {

    let helper = SendGrid.mail;

    let from_email: any = new helper.Email(process.env.FROM_EMAIL);
    let to_email: any = new helper.Email(toEmail);
    let helperContent: any = new helper.Content("text/plain", content);
    let mail: any = new helper.Mail(from_email, subject, to_email, helperContent)

    var request = SendGrid.emptyRequest({
        method: "POST",
        path: "/v3/mail/send",
        body: mail.toJSON()
    });

    //This performs the request with a promise
    SendGrid.API(request).then((response: any) => {
        //Deal with output as needed
        console.log("email was sent!!");
    }).catch((err: any) => {
        //log.error(err);
    });
}

然后,在我的 index.ts 上,我有以下声明:

export * from "./email";
export * from "./errors";
export * from "./logger";
export * from "./objectUtils";
export * from "./queryFilter";
export * from "./templateEngine";
export * from "./utils";

在我导入此模块的应用程序中,我将其导入为

import * as Utils from "my-utils";

最后,每当我想使用 sendEmail 函数时,我都会使用以下语句调用它:

Utils.sendEmail(email, subject, content);

但是,这总是会引发错误,指出 "Cannot read property 'sendEmail' of undefined"

为什么会这样?以这种方式导出时,我不应该能够使用这种类型的声明吗? 解决办法是什么?

最好的问候

【问题讨论】:

  • 这是什么my-utils
  • @NitzanTomer 这是我的 NPM 模块的名称
  • 似乎节点找不到您的模块。看看编译后的输出,有意义吗?你能把它包括在你的问题中吗?
  • @NitzanTomer 答案是删除“默认”关键字。查看接受的解决方案。

标签: node.js typescript node-modules


【解决方案1】:

尝试改变

export default function sendEmail

只是

export function sendEmail

【讨论】:

  • 这正是我所做的。删除了所有默认声明,甚至在看到您的答案和所有声明按预期工作之前。 Tks
  • 投了反对票!调用 util 方法呢?为什么没有添加它的用法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 2020-03-11
  • 2015-05-08
  • 2012-11-06
相关资源
最近更新 更多