Last active
May 30, 2026 19:49
-
-
Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
132 bytes i18n in Nuxt.js
This file contains hidden or 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
| // export function useI18n(translations) { | |
| // return (key, ...args) => { | |
| // const value = key.trim().split('.').reduce((obj, k) => obj?.[k], translations) ?? key | |
| // return typeof value === 'function' ? value(...args) : value | |
| // } | |
| // } | |
| export function useI18n(t){return(n,...e)=>{const r=n.trim().split('.').reduce(((t,n)=>t?.[n]),t)??n;return'function'==typeof r?r(...e):r}} | |
| export const t = (x, y) => useRoute().meta.t(x, y) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of wrapping
useRoute().meta.t, it is much safer in Nuxt to assign a computed or context-bound composable, or use Nuxt's provide/inject payload footprint. For instance, creating a custom composable:And inside your component template:
If you want to push the "132 bytes" constraint even further, you can strip the .trim() call unless you explicitly anticipate developers typing spaces around key paths (like t(' welcome.title ')). Removing .trim() saves around 10–12 bytes minified.
Using a short ternary instead of typeof r === 'function' can also save room, although checking constructor names can occasionally be fragile if things are cross-compiled:
A robust, runtime-safe version that is still incredibly small but eliminates potential crashes from an undefined translations reference or invalid keys: