If you read the docs carefull under Using with Express.js, it's clearly documented how it's used. After you bind i18n
to express app through i18n.expressBind
, i18n
is available through the req
object available to all express middlewares like:
req.i18n.__("My Site Title")
So somefunction
should either be a middleware like:
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???
}
Or you need to explicitly pass in the req
object through a middleware like:
function somefunction(req) {
const message = req.i18n.__("no_user_to_select") + "???";
// outputs -> no_user_to_select???
}
app.use((req, res, next) => {
somefunction(req);
});
If you want to use i18n
directly you need to instantiate
it as documented like
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???
}
Many discourage use of 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');