Last active
October 24, 2021 21:33
-
-
Save james2doyle/d00e06a5f4963a539e3aa0b2d5283d11 to your computer and use it in GitHub Desktop.
An incredibly simple i18n translation function using lodash `get` and `template` functions
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
/** | |
* An incredibly simple i18n translation function using lodash `get` and `template` functions | |
* | |
* if `key.hello-message` was "Hello {msg}!" | |
* | |
* intl('key.hello-message', { msg: 'world' }) // "Hello world!" | |
*/ | |
import { get, template, memoize } from 'lodash'; | |
// @ references root project dir | |
const en = require('@/lang/en.json'); | |
/** | |
* Translate a string from a preloaded JSON document | |
*/ | |
function intl(key: string, values: Record<string, string | number> = {}): string { | |
const compiled = template(get(en, key), { | |
interpolate: /{([\s\S]+?)}/g, // {myVar} | |
}); | |
return compiled(values); | |
}; | |
export default memoize(intl); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment