Skip to content

Commit

Permalink
docs(readme): add glob import
Browse files Browse the repository at this point in the history
  • Loading branch information
crimx committed Jul 20, 2023
1 parent e85f428 commit bb132b6
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,41 @@ if (import.meta.hot) {
}
```

## Dynamic Import

Although you can simply use `import()` to dynamically load locales, with bundler API you can do more.

For example with Vite you can use [glob import](https://vitejs.dev/guide/features.html#glob-import) to statically get info of all locales.
This way allows you to add or remove locales without changing source code.

```ts
import { I18n, detectLang, type Locale, type LocaleLang } from "val-i18n";

export const i18nLoader = (): Promise<I18n> => {
const localeModules = import.meta.glob<boolean, string, Locale>(
"./locales/*.json",
{ import: "default" }
);

const localeLoaders = Object.keys(localeModules).reduce((loaders, path) => {
if (localeModules[path]) {
const langMatch = path.match(/\/([^/]+)\.json$/);
if (langMatch) {
loaders[langMatch[1]] = localeModules[path];
}
}
return loaders;
}, {} as Record<LocaleLang, () => Promise<Locale>>);

const langs = Object.keys(localeLoaders);

return I18n.preload(
detectLang(langs) || (localeLoaders.en ? "en" : langs[0]),
lang => localeLoaders[lang]()
);
};
```

## Framework Integration

### Svelte
Expand Down

0 comments on commit bb132b6

Please sign in to comment.