Skip to content

Commit

Permalink
feat: add meaningful error when locale is not set
Browse files Browse the repository at this point in the history
  • Loading branch information
timofei-iatsenko committed Dec 21, 2024
1 parent e45a2af commit 158b020
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/core/src/i18n.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,4 +431,17 @@ describe("I18n", () => {
expect(i18n._("Software development")).toEqual("Software­entwicklung")
expect(i18n._("Software development")).toEqual("Software­entwicklung")
})

it("._ should throw a meaningful error when locale is not set", () => {
const i18n = setupI18n({})
expect(() =>
i18n._(
"Text {0, plural, offset:1 =0 {No books} =1 {1 book} other {# books}}"
)
).toThrowErrorMatchingInlineSnapshot(`
"Lingui: Attempted to call a translation function without setting a locale.
Make sure to call \`i18n.activate(locale)\` before using Lingui functions.
This issue may also occur due to a race condition in your initialization logic."
`)
})
})
8 changes: 8 additions & 0 deletions packages/core/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,14 @@ export class I18n extends EventEmitter<Events> {
values?: Values,
options?: MessageOptions
): string {
if (!this.locale) {
throw new Error(
"Lingui: Attempted to call a translation function without setting a locale.\n" +
"Make sure to call `i18n.activate(locale)` before using Lingui functions.\n" +
"This issue may also occur due to a race condition in your initialization logic."
)
}

let message = options?.message

if (!id) {
Expand Down
5 changes: 5 additions & 0 deletions packages/vite-plugin/test/macro-usage/entrypoint.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { t } from "@lingui/core/macro"
import { i18n } from "@lingui/core"

export async function load() {
i18n.loadAndActivate({
locale: "en",
messages: {},
})
return t`Ola`
}

0 comments on commit 158b020

Please sign in to comment.