Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add meaningful error when locale is not set #2131

Merged
merged 1 commit into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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`
}
Loading