In this episode, we're building a super lightweight JavaScript translation helper that mimics the familiar Laravel translation functionality, but for our frontend. We start off by creating a new file, lang.js
, which exports a function (we call it __
) to look up translation keys and handle replacement attributes (like user names in greetings).
We make this function globally available to all our Vue components by adding it to the app instance's global properties. That way, we can use it anywhere in our app without having to import it each time.
Next, we wire up the function to actually fetch translations using data that's already passed to our app as props. If a key we try to access doesn't exist, our helper just returns the key itself—super handy for debugging missing translations.
The core challenge is supporting dynamic replacements (like injecting a name into a welcome message). We add support for an object of replacements, then use JavaScript's string replace
method to sub in the correct values wherever we have :attribute
placeholders in our translations.
We finish by showing that everything reacts nicely: switching languages updates the UI instantly, and trying a missing key just spits out the key (not an error). Bonus: you don't need to pull in any heavy libraries—this tiny helper gets you most of the way for typical translation scenarios!
If you need more advanced i18n stuff later, you can easily upgrade, but for now, we have a clean and simple translation solution that just works.