node.js i18n: Use __ or import?

Marty

I am new to i18n and have an existing repository that uses it. I noticed different syntax for using i18n throughout the repository and am wondering what is the best way.

I am confused about the structure below and which syntax option is best (I think it's better to be consistent with the syntax and use only 1 option). Could someone perhaps explain?

In controllers I find:

var responses = require('../../locales/en.json');

let message = responses.authorisation.flashes['welcome'];
return res.status(200).json({
  success: true,
  message,
  token,
  user: userData
});

In middleware the syntax is as follows:

req.flash('error', req.__('organisation.not-found'));

And in app.js I find:

const flash = require('connect-flash');
const flashMiddleware = require('./middleware/flashMiddleware');

const i18n = require('i18n');
i18n.configure({
  locales: [
    'en', 'nl'
  ],
  register: global,
  directory: path.join(__dirname, 'locales'),
  defaultLocale: 'en',
  objectNotation: true,
  updateFiles: false
});

flashMiddleware.js contains (I'm not sure what this does):

const flashMiddleware = (req, res, next) => {
  res.locals.flashes = req.flash();

  next();
};

module.exports = flashMiddleware;
T.J. Crowder

Both your first and last code blocks don't appear to be using i18n at all. Instead, the first code block is loading the JSON for en and using it directly. It's not clear what the flash stuff is using, I don't see anything in that code doing localization.

The middleware syntax, using __ on req, appears to be the standard way you use this library in middleware.

There are other ways to use it as well that are detailed in the documentation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related