i18n.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.$$ = exports.i18nLoader = void 0;
  7. const fs_1 = __importDefault(require("fs"));
  8. class i18nLoader {
  9. constructor(locale) {
  10. this.locale = locale;
  11. this.map = {};
  12. }
  13. static getInstance(locale) {
  14. if (!i18nLoader.instance)
  15. i18nLoader.instance = new i18nLoader(locale !== null && locale !== void 0 ? locale : i18nLoader.defaultLocale);
  16. return i18nLoader.instance;
  17. }
  18. setLocale(locale) {
  19. this.locale = locale;
  20. return this;
  21. }
  22. load(...paths) {
  23. for (const p of paths) {
  24. try {
  25. const data = fs_1.default.readFileSync(p).toString('utf8');
  26. try {
  27. this.loadJson(JSON.parse(data));
  28. }
  29. catch (err) {
  30. console.error('JSON parsing error:', err);
  31. }
  32. }
  33. catch (error) {
  34. console.error(`i18n file '${p}' not found.`, error);
  35. }
  36. }
  37. return this;
  38. }
  39. loadJson(obj) {
  40. for (const locale of Object.keys(obj)) {
  41. if (!this.map[locale])
  42. this.map[locale] = {};
  43. for (const key of Object.keys(obj[locale]))
  44. this.map[locale][key] = obj[locale][key];
  45. }
  46. return this;
  47. }
  48. get(key) {
  49. var _a;
  50. let value;
  51. if (!this.map[this.locale] && !this.map[i18nLoader.defaultLocale])
  52. return key;
  53. if (this.map[i18nLoader.defaultLocale])
  54. value = this.map[i18nLoader.defaultLocale][key];
  55. if (this.map[this.locale])
  56. value = (_a = this.map[this.locale][key]) !== null && _a !== void 0 ? _a : value;
  57. return value !== null && value !== void 0 ? value : key;
  58. }
  59. }
  60. exports.i18nLoader = i18nLoader;
  61. i18nLoader.defaultLocale = 'en_US';
  62. const $$ = (key, params) => {
  63. let text = i18nLoader.getInstance().get(key);
  64. if (params) {
  65. for (const param of Object.keys(params)) {
  66. const regex = new RegExp(`\{${param}\}`, 'g');
  67. text = text.replace(regex, params[param]);
  68. }
  69. }
  70. return text;
  71. };
  72. exports.$$ = $$;
  73. //# sourceMappingURL=i18n.js.map