Feliday-UI/generate_translations.js

69 lines
1.8 KiB
JavaScript
Raw Normal View History

2021-03-01 20:00:43 +00:00
const fs = require("fs");
2021-03-01 20:00:43 +00:00
const translationDir = "lemmy-translations/translations/";
const outDir = "src/shared/translations/";
fs.mkdirSync(outDir, { recursive: true });
2021-01-06 21:06:13 +00:00
fs.readdir(translationDir, (_err, files) => {
files.forEach(filename => {
2021-03-01 20:00:43 +00:00
const lang = filename.split(".")[0];
try {
const json = JSON.parse(
2021-03-01 20:00:43 +00:00
fs.readFileSync(translationDir + filename, "utf8")
);
2021-03-01 20:00:43 +00:00
let data = `export const ${lang} = {\n translation: {`;
for (const key in json) {
if (key in json) {
const value = json[key].replace(/"/g, '\\"');
2021-03-01 20:00:43 +00:00
data += `\n ${key}: "${value}",`;
}
}
2021-03-01 20:00:43 +00:00
data += "\n },\n};";
const target = outDir + lang + ".ts";
fs.writeFileSync(target, data);
} catch (err) {
console.error(err);
}
});
});
2021-03-01 20:00:43 +00:00
// generate types for i18n keys
const baseLanguage = "en";
fs.readFile(`${translationDir}${baseLanguage}.json`, "utf8", (_, fileStr) => {
const keys = Object.keys(JSON.parse(fileStr));
2021-03-01 20:33:57 +00:00
const data = `import { i18n } from "i18next";
2021-03-01 20:00:43 +00:00
declare module "i18next" {
2021-03-01 20:33:57 +00:00
export type I18nKeys =
${keys.map(key => ` | "${key}"`).join("\n")};
export interface TFunctionTyped {
2021-03-01 20:00:43 +00:00
// basic usage
<
TResult extends TFunctionResult = string,
2021-03-01 20:33:57 +00:00
TInterpolationMap extends Record<string, unknown> = StringMap
2021-03-01 20:00:43 +00:00
>(
key: I18nKeys | I18nKeys[],
options?: TOptions<TInterpolationMap> | string
): TResult;
// overloaded usage
<
TResult extends TFunctionResult = string,
2021-03-01 20:33:57 +00:00
TInterpolationMap extends Record<string, unknown> = StringMap
2021-03-01 20:00:43 +00:00
>(
key: I18nKeys | I18nKeys[],
defaultValue?: string,
options?: TOptions<TInterpolationMap> | string
): TResult;
}
2021-03-01 20:33:57 +00:00
export interface i18nTyped extends i18n {
t: TFunctionTyped;
}
2021-03-01 20:00:43 +00:00
}
`;
fs.writeFileSync(`${outDir}i18next.d.ts`, data);
});