预先感谢您的帮助。
我不确定如何执行以下操作。我有一个发送电子邮件的模块,并且使用summon.js依赖项注入将Config注入到模块中,但是我需要使用sendMail方法并将参数mailOptions传递给它。这是代码示例:
'use strict';
const nodemailer = require('nodemailer');
const ejs = require('ejs');
const fs = require('fs');
module.exports = function(Configs) {
// create reusable transporter object using the default SMTP transport
let transporter = nodemailer.createTransport({
host: Configs.email.host,
port: Configs.email.port,
auth: {
user: Configs.email.user,
pass: Configs.email.pass
}
});
this.sendMail = function(mailOptions) {
mailOptions.to = Configs.mockEmail || mailOptions.to
mailOptions.from = Configs.email.user
return new Promise((resolve, reject) => {
if (mailOptions.template) {
ejs.renderFile('/../templates/' + mailOptions.template +
'.ejs', mailOptions.data, null, (err, html) => {
if (err) {
return reject(err)
}
resolve(html)
})
return
}
resolve()
}).then(html => {
mailOptions.html = html || mailOptions.html
return new Promise((resolve, reject) => {
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return reject(error)
}
resolve(info)
})
})
})
}
return this
}
然后,我要使用此模块:
const EmailUtil = require('email')
async function foo() {
// Do something async with await.
const mailOptions = {...}
EmailUtils.sendMail(mailOption);
}
但是,它给了我错误:
TypeError: EmailUtils.sendMail is not a function
注意:我可以删除module.export = function(Configs),但它们并不是很好,因为我需要对配置文件的路径进行硬编码,并且每个环境都有多个配置文件。然后,我希望能够在从另一个模块调用sendMail时保持Summon.js依赖关系注入。谢谢
有什么想法吗? 谢谢!
答案 0 :(得分:1)
由于要导出函数,因此需要在需要模块之后实际调用它:
class FbPage extends WP_Widget
{
public $fb_services;
public $widget_ID;
public $widget_name;
public $widget_options = array();
public $control_options = array();
public function __construct()
{
$this->widget_ID = 'fb_page';
$this->widget_name = 'Facebook Page';
$this->widget_options = array(
'classname' => $this->widget_ID,
'description' => 'Widget of Facebook Page',
'customize_selective_refresh' => true
);
$this->control_options = array();
$this->fb_services = new FacebookServices();
}
答案 1 :(得分:1)
使用this
暗示应该将一个函数用作构造函数。仅当用this
调用函数或将其绑定到某个上下文时,才需要new
对象。
JavaScript中有一个约定,即使用Pascal大小写的名称作为构造函数的名称,因此可以在代码中明确标识它们。
对于给定的EmailUtil
,应该为:
const EmailUtil = require('email');
const emailUtil = new EmailUtil(config);
...
emailUtil.sendMail(mailOption);
答案 2 :(得分:0)
我通过在Depend.json文件中包含EmailUtils来回答这个问题,该文件负责定义summonjs的依赖关系。这样,我便能够将配置传递给EmailUtils并以这种方式调用sendMail。
EmailUtils.sendMail(mailOptions);
不需要使用关键字new,这是一个很好的答案。我不知道可以用这种方式实例化模块。