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
- Read the Contributing Guidelines
- Read the Documentation
- Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
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.
@intlify/cli
: https://github.com/intlify/cli/blob/main/src/i18n.ts@intlify/h3
: https://github.com/intlify/h3/blob/main/src/index.ts
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.