![](/img/trans.png)
[英]CommonJS Illegal invocation error when calling function on module.exports
[英]Migrating a CommonJS 'module.exports = function()' to ESM
我正在使用 NodeJS,並且已經編寫 JavaScript 幾年了,並且仍在學習。
對於我的 CJS 模塊,我編寫(我稱之為)一個包含所有(我稱之為)我的子函數的根函數,然后在我想要公開的函數的根函數上return {subfunction1, subfunction2}
。 不可否認,我從Jonathan Mills那里學到了這種寫作風格,並且對它很滿意。
我正在努力解決如何將其從 CommonJS 正確遷移到 ESM 並且希望在不使用Class
的情況下這樣做。 但是,如果Class
是 ESM 的正確方式,那么我會適應。
這是一個 CJS 服務:
service.js
function WebexService(webex) {
async function processMessage(messageData) {
try {
const user = await webex.people.get(messageData.personId);
//debug(user);
sendMessage({ displayName: user.displayName, roomId: messageData.roomId });
} catch (error) {
debug(error);
throw error;
}
}
function sendMessage(messageInfo) {
webex.messages.create({
roomId: messageInfo.roomId,
text: `Howdy! ${messageInfo.displayName}`,
});
}
return { processMessage }
}
module.exports = WebexService()
要使用此 CJS 服務,我會將其導入為:
app.js
const { processMessage } = require('../services/webexService');
function superCool() {
const messageResponse = await processMessage(messageData);
}
我能夠讓它與 ESM 一起工作的唯一方法是作為一個Class
:
service.js
import debugInit from 'debug';
import chalk from 'chalk';
const debug = debugInit('app:services:webex');
export default class WebexService {
constructor(webex) {
this.webex = webex;
}
async processMessage(messageData) {
try {
const user = await this.webex.people.get(messageData.personId);
//debug(user);
this.sendMessage({ displayName: user.displayName, roomId: messageData.roomId });
} catch (error) {
debug(error);
throw error;
}
}
sendMessage(messageInfo) {
this.webex.messages.create({
roomId: messageInfo.roomId,
text: `Howdy! ${messageInfo.displayName}`,
});
}
}
app.js
import WebexService from '../services/webex.js';
const WebexServiceInstance = new WebexService(webex);
WebexServiceInstance.processMessage(event.data);
我希望有人能指出我正確的方向。 如果有人可以幫助我找到一個可以閱讀的內容,我很高興 RTFM。
service.js
function WebexService(webex) {
async function processMessage(messageData) {
try {
const user = await webex.people.get(messageData.personId);
//debug(user);
sendMessage({ displayName: user.displayName, roomId: messageData.roomId });
} catch (error) {
debug(error);
throw error;
}
}
function sendMessage(messageInfo) {
webex.messages.create({
roomId: messageInfo.roomId,
text: `Howdy! ${messageInfo.displayName}`,
});
}
return { processMessage }
}
const service = WebexService()
export default service
app.js
import WebexService from '../services/webex.js';
// you can then do this
const { processMessage } = WebexService;
function superCool() {
const messageResponse = await processMessage(messageData);
}
// or just use it directly
function superCool() {
const messageResponse = await WebexService.processMessage(messageData);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.