Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active May 30, 2026 19:49
Show Gist options
  • Select an option

  • Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.

Select an option

Save daliborgogic/1b3b7468d1afb8a67bcab7ca2091a705 to your computer and use it in GitHub Desktop.
132 bytes i18n in Nuxt.js
// 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)
@daliborgogic
Copy link
Copy Markdown
Author

daliborgogic commented May 30, 2026

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:

// composables/useT.ts
export const useT = () => {
  const route = useRoute()
  return (key, ...args) => route.meta.t?.(key, ...args) ?? key
}

And inside your component template:

<script setup>
const t = useT()
</script>

<template>
  {{ t('welcome') }}
</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:

// Instead of: 'function'==typeof r?r(...e):r
// You can use: r instanceof Function?r(...e):r

A robust, runtime-safe version that is still incredibly small but eliminates potential crashes from an undefined translations reference or invalid keys:

export function useI18n(t = {}) {
  return (k, ...e) => {
    const r = t[k] ?? k.split('.').reduce((o, s) => o?.[s], t) ?? k;
    return r instanceof Function ? r(...e) : r;
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment