我正在尝试瞄准,这样我就可以在被调用的函数中使用i18n。
我有一个错误:
(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function我怎样才能让i18n在函数中工作,而不是在请求中?
Server.js:
var i18n = require('i18n-2');
global.i18n = i18n;
i18n.expressBind(app, {
// setup some locales - other locales default to en silently
locales: ['en', 'no'],
// change the cookie name from 'lang' to 'locale'
cookieName: 'locale'
});
app.use(function(req, res, next) {
req.i18n.setLocaleFromCookie();
next();
});
//CALL another file with some something here.otherfile.js:
somefunction() {
message = i18n.__("no_user_to_select") + "???";
}我该如何解决这个问题?
发布于 2019-04-13 01:39:53
如果您仔细阅读Using with Express.js下的文档,就会清楚地了解它是如何使用的。在通过i18n.expressBind将i18n绑定到express应用程序之后,所有express中间件都可以通过req对象使用i18n:
req.i18n.__("My Site Title")所以somefunction应该是一个中间件,如下所示:
function somefunction(req, res, next) {
// notice how its invoked through the req object
const message = req.i18n.__("no_user_to_select") + "???";
// outputs -> no_user_to_select???
}或者,您需要通过中间件显式地传递req对象,例如:
function somefunction(req) {
const message = req.i18n.__("no_user_to_select") + "???";
// outputs -> no_user_to_select???
}
app.use((req, res, next) => {
somefunction(req);
});如果您想要直接使用i18n,则需要按照文档所示对其执行instantiate操作,如下所示
const I18n = require('i18n-2');
// make an instance with options
var i18n = new I18n({
// setup some locales - other locales default to the first locale
locales: ['en', 'de']
});
// set it to global as in your question
// but many advise not to use global
global.i18n = i18n;
// use anywhere
somefunction() {
const message = i18n.__("no_user_to_select") + "???";
// outputs -> no_user_to_select???
}许多人不鼓励使用global。
// international.js
// you can also export and import
const I18n = require('i18n-2');
// make an instance with options
var i18n = new I18n({
// setup some locales - other locales default to the first locale
locales: ['en', 'de']
});
module.exports = i18n;
// import wherever necessary
const { i18n } = require('./international');https://stackoverflow.com/questions/55502598
复制相似问题