Skip to content

Commit

Permalink
feat: logLevel option
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed May 22, 2023
1 parent 6faa3f1 commit d925e9e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,39 @@ const CONSOLE_PREFIX = '[vue-i18n]'
export const injectionKey = Symbol('i18n') as InjectionKey<UseI18n>

export function createI18n(config: I18nConfig): I18nInstance {
const { defaultLocale = 'en' } = config
const {
defaultLocale = 'en',
logLevel = 'warn',
} = config
const messages = reactive(klona(config.messages ?? {}))
const locale = ref(defaultLocale)
const locales = config.locales ?? (Object.keys(messages).length ? Object.keys(messages) : [locale.value])

const t = (key: string, params?: Record<string, any>) => {
if (typeof key !== 'string') {
console.warn(CONSOLE_PREFIX, `Message "${key}" must be a string`)
if (logLevel === 'warn')
console.warn(CONSOLE_PREFIX, `Message "${key}" must be a string`)
return ''
}

try {
return getLocalizedMessage(key.split('.'), messages[locale.value], params)
}
catch (error) {
console.warn(CONSOLE_PREFIX, (error as Error).message)
if (logLevel === 'warn')
console.warn(CONSOLE_PREFIX, (error as Error).message)
return key
}
}

const setLocale = (newLocale: string) => {
if (!locales.includes(newLocale)) {
console.warn(
CONSOLE_PREFIX,
if (logLevel === 'warn') {
console.warn(
CONSOLE_PREFIX,
`Locale "${newLocale}" is not defined in the locales list. Available locales: ${locales.join(', ')}`,
)
)
}
return
}

Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export interface I18nConfig {
defaultLocale?: string
locales?: string[]
messages?: LocaleMessages
/** @default 'warn' */
logLevel?: 'warn' | 'silent'
}

export interface I18nInstance {
Expand Down

0 comments on commit d925e9e

Please sign in to comment.