Getting started

Installation

Install svelte-intl-precompile as a runtime dependency of your sveltkit app.

  
npm install svelte-intl-precompile

Create your translations

Next create a folder to put your translations files in. I like to use /messages or /locales at the root of the project, but really any folder will do.

  
├── locales │   ├── en.json │   ├── es.json ├── src ... ├── static ├── package.json └── svelte.config.js

I recommend using JSON files but you can use use javascript with an object as their default export. Whatever the file extension, you translations inside are just regular strings in the ICU message syntax:

  
{ "recent.aria": "Find recently viewed tides", "menu": "Menu", "foot": "{count} {count, plural, =1 {foot} other {feet}}", }

I prefer when the dictionary has a single level and using dots to create hierarchies like in the one above, but you can also nest objects like in the next example:

  
{ "placeholders": { "fullname": "John Smith", "street-name": "13 Elm Street", "subject": "Re: Hello" }, "welcome-hero": "Welcome to Goliath Bank!", }

JSON is too constrained! I want more flexibility!

You can also use JSON 5 features in your json files. That is, you can have comments, multi-line strings, single quotes, trailing commas...
It just works out of the box.

I don't like curly braces

Fair enough. If you like significant whitespace you can also use YAML files. Just use the .yaml or .yml extension names. If you are into that sort of things.

I want even more features

You can also define your translation in .js files, .ts files and .mjs files. Your module must export the object with the translations as its default export.

Hook the compiler into SvelteKit

This library's build time compiler needs to hook into the build pipeline of your app. For that, add it to the list of vite plugins in your /svelte.config.js

  
import precompileIntl from "svelte-intl-precompile/sveltekit-plugin"; const config = { kit: { target: '#svelte', vite: { plugins: [ precompileIntl('locales') // if your translations are defined in /locales/[lang].json ] } } }; export default config;

You are set, time to use the library.

Hook the compiler into plain Vite.js

If you are not using SvelteKit but raw Vite.js, the configuration is very similar. At the end SvelteKit uses Vite.js underneath. Import the compiler and pass it to the list of plugins in /vite.config.js

  
import { defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; import precompileIntl from "svelte-intl-precompile/sveltekit-plugin"; export default defineConfig({ resolve: { dedupe: ["svelte"] }, plugins: [ svelte(), precompileIntl("locales"), ], });