[英]node.js i18n: “ReferenceError: __ is not defined”
在我的整個應用程序中,我毫無問題地使用i18n
。 但是,對於 email 通過 cron 作業發送,我收到錯誤:
ReferenceError: __ 未定義
在app.js
我配置 i18n:
const i18n = require("i18n");
i18n.configure({
locales: ["en"],
register: global,
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
objectNotation: true,
updateFiles: false,
});
app.use(i18n.init);
在我的整個應用程序中,我將它用作__('authentication.flashes.not-logged-in')
,就像我說的沒有問題。 在由 cron 作業調用的郵件 controller 中,我以相同的方式使用它: __('mailers.buttons.upgrade-now')
。 然而,只有在那里,它才會產生上述錯誤。
只是為了嘗試,我在郵件 controller 中將其更改為i18n.__('authentication.flashes.not-logged-in')
。 但后來我得到另一個錯誤:
(node:11058) UnhandledPromiseRejectionWarning: TypeError: logWarnFn is not a function
at logWarn (/data/web/my_app/node_modules/i18n/i18n.js:1180:5)
知道如何使通過 cron 作業發送的電子郵件正常工作嗎?
在評論中,提問者澄清說,cron 作業直接調用mailController.executeCrons()
,而不是向應用程序發出 HTTP 請求。 因此, i18n
全局 object 永遠不會被定義,因為app.js
中的應用程序設置代碼沒有運行。
最好的解決方案是使用i18n
的實例用法。 You could separate the instantiation and configuration of an I18N
object out into a separate function, then call it both in app.js
to set it up as Express middleware, and in the mailController.executeCrons()
function to use it when being called through the定時任務。
代碼大綱:
i18n.js
(新文件)
const i18n = require("i18n");
// factory function for centralizing config;
// either register i18n for global use in handling HTTP requests,
// or register it as `i18nObj` for local CLI use
const configureI18n = (isGlobal) => {
let i18nObj = {};
i18n.configure({
locales: ["en"],
register: isGlobal ? global : i18nObj,
directory: path.join(__dirname, "locales"),
defaultLocale: "en",
objectNotation: true,
updateFiles: false,
});
return [i18n, i18nObj];
};
module.exports = configureI18n;
app.js
const configureI18n = require('./path/to/i18n.js');
const [i18n, _] = configureI18n(true);
app.use(i18n.init);
mailController.js
const configureI18n = require('./path/to/i18n.js');
const [_, i18nObj] = configureI18n(false);
executeCrons() {
i18nObj.__('authentication.flashes.not-logged-in');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.