@colisweb/rescript-toolkit
Version:

64 lines (55 loc) • 1.82 kB
JavaScript
const fs = require("fs");
const cp = require("child_process");
const path = require("path");
const cwd = process.cwd();
const src = path.join(cwd, "src");
const localeFolderPath = path.join(cwd, "locale");
const AVAILABLE_LANGUAGES = ["fr"];
const DEFAULT_LANGUAGE = "fr";
if (!fs.existsSync(localeFolderPath)) {
fs.mkdirSync(localeFolderPath);
}
const bin = path.join(cwd, "node_modules", ".bin", "bs-react-intl-extractor");
console.log("=== ⏳ Extracting messages...");
const extracted = JSON.parse(
cp.execSync(`${bin} --allow-duplicates ${src} ${localeFolderPath}`)
);
console.log("=== ✅ Extracting messages... done.");
for (const LANGUAGE of AVAILABLE_LANGUAGES) {
console.log(`\n=== ⏳ Updating ${LANGUAGE} translation...`);
const file = path.join(src, "../locale", `${LANGUAGE}.json`);
let content;
try {
if (fs.existsSync(file)) {
content = JSON.parse(fs.readFileSync(file));
} else {
console.log(
`=== ⚠️ Translation for ${LANGUAGE} wasn't found. Creating new one.`
);
content = [];
}
} catch (error) {
console.log(error.code);
if (error.code === "ENOENT") {
console.log(
`=== ⚠️ Translation for ${LANGUAGE} wasn't found. Creating new one.`
);
content = [];
} else {
throw error;
}
}
const cache = content.reduce((acc, msg) => ({ ...acc, [msg.id]: msg }), {});
const messages = extracted.map((msg) => ({
id: msg.id,
defaultMessage: msg.defaultMessage,
message:
cache[msg.id] && cache[msg.id].message
? cache[msg.id].message
: LANGUAGE === DEFAULT_LANGUAGE
? msg.defaultMessage
: "",
}));
fs.writeFileSync(file, JSON.stringify(messages, null, 2) + "\n");
console.log(`=== ✅ Updating ${LANGUAGE} translation... done.`);
}