date-fns:如何在整个应用程序范围内定义默认语言环境?

date-fns: how to define a default locale app-wide?

在每个函数调用的基础上设置语言环境非常简单:

import { formatRelative, subDays } from 'date-fns'
import { ptBR } from 'date-fns/locale'

formatRelative(subDays(new Date(), 3), new Date(), { locale: ptBR })

但是如何设置在整个应用程序范围内使用的默认语言环境?

据我所知,没有这样的选项。通常我围绕 formatDate 函数创建自定义包装函数并向其传递应用程序区域设置。您可以将区域设置存储在全局变量或应用程序级存储中:

formatRelativeWrap.js

import { formatRelative } from 'date-fns'
import AppStore from 'appStore'

export default (date1, date2, locale) => {
    return formatRelative(date1, date2, { locale: locale || AppStore.defaultLocale})
}

作为 @Pointy mentioned there is note about this in official docs - https://date-fns.org/v2.22.1/docs/I18n - 第二个例子。