EasyTranslate.js is a lightweight JavaScript library for easy message translation based on language and translation groups.
You can install EasyTranslate.js via npm:
npm install easytranslate.js
const Translator = require('easytranslate.js');
// Create an instance of the Translator
const translator = new Translator();
// Set the directory containing translation files
translator.setDirectory('./translations');
// Optional: Set a custom message for when a translation is not found
translator.setNotFoundMessage('Translation not available!');
// Optional: Enable debug mode to log additional information
translator.setDebugMode(true);
// Get available languages
const availableLanguages = translator.getAvailableLanguages();
console.log('Available Languages:', availableLanguages);
// Translate a message
const translation = translator.translate('en', 'greetings.user.header.title1', { user: 'me', time: '10 pm' });
console.log('Translation:', translation);
Place your translation files in the specified directory (e.g., ./translations). Each file should be named with the language code (e.g., en.json) and follow the JSON structure:
{
"greetings": {
"user": {
"header": {
"title1": "Hey {user}, it is {time}?"
}
}
}
}
getAvailableLanguages(): string[]
translate(language: string, key: string, params?: object): string