Last active
August 12, 2021 08:28
-
-
Save click2install/9b21a272ab946b8fdfa36c4f89e6f09f to your computer and use it in GitHub Desktop.
[i18nKeyGenerator] - Build utility for generating a typed object for typed access to i18n keys.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// util to code generate an object from another object where all the resulting object | |
// keys equal their respective paths within the object. | |
// | |
// useful for removing magic i18n strings from code. | |
/* eslint-disable @typescript-eslint/no-var-requires */ | |
const dot = require("dot-object"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const json = require("./en.json"); | |
/* eslint-enable @typescript-eslint/no-var-requires */ | |
// turn json object into dotted property paths like | |
// | |
// { | |
// someKey: "someValue", | |
// "some.nested.key": "someNestedValue" | |
// } | |
const obj = dot.dot(json); | |
// transform schema object values to equal the keys | |
const schema = Object.fromEntries(Object.entries(obj).map(([key]) => [key, key])); | |
// turn schema back into a nested object | |
const result = dot.object(schema); | |
// regex to remove the `"` from around the JSON keys | |
const regex = /"(\w+)":(\s?(.+))|({),/gm; | |
const str = ` | |
export const i18nKeys = | |
${JSON.stringify(result, null, 2).replace(regex, match => | |
{ | |
const [key, value] = match.split(":"); | |
return `${key.replace(/"/g, "")}: ${value}`; | |
})};`; | |
fs.writeFileSync(path.join(__dirname, "./", "i18nKeys.ts"), str); | |
// run using npm scripts, with or without i18next-scanner | |
"scripts": { | |
"i18n:scan": "npx i18next-scanner --config ./i18next-scanner.config.js && npm run i18n:keys", | |
"i18n:keys": "node ./src/i18n/i18nKeysGenerator.js" | |
} | |
// USAGE: | |
import { i18nKeys } from "./i18n/i18nKeys"; | |
function Test() { | |
return <Button>{t(i18nKeys.labels.today)}</Button> | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment