intlify/vue-i18n

How to use `@intlify/core` in NodeJS

mahnunchik opened this issue · 2 comments

Clear and concise description of the problem

Could you please add code samples and/or documentation how to use @intlify/core in bare NodeJS app.

Suggested solution

Code samples or documentation or tests in the repo https://github.com/intlify/vue-i18n-next/tree/master/packages/core

Alternative

No response

Additional context

It would be helpful to use the same i18n system in vue app and server side code.

Validations

Thank you for your feedback!

We are planning to migrate @intlify/core from vue-i18n-next to a separate package to make it completely framework-agnostic in the future. We will have it documented at that time.

There is no documentation, but here are some real world packages where @intlify/core is used. It may be of interest to you.

My example code of using @intlify/core in Telegram bot:

// i18n.js
import {
  createCoreContext,
  number,
  translate,
} from '@intlify/core';

import datetimeFormats from './datetimeFormats.js';
import numberFormats from './numberFormats.js';
import pluralRules from './pluralRules.js';

const messages = {};
// load messages

const contexts = new Map();

export function i18n(locale) {
  if (!contexts.has(locale)) {
    contexts.set(locale, createCoreContext({
      locale: locale,
      messages,
      datetimeFormats,
      numberFormats,
      pluralRules,
    }));
  }
  const i18nContext = contexts.get(locale);
  return {
    t(key, ...args) {
      return translate(i18nContext, key, ...args);
    },
    n(value, ...args) {
      return number(i18nContext, value, ...args);
    },
  };
}

Usage:

bot.use(async (ctx, next) => {
  // make t and n available on context
  Object.assign(ctx, i18n(ctx.user.locale));
  return next();
});

This allow me to share almost all translation logic between vue app and server side bot related code.