无法“动态”导入 date-fns/locale 库 - TypeScript 给出尝试导入错误

Whi*_*ann 11 javascript import locale typescript date-fns

我有一个应用程序从后端接收支持的区域设置列表作为以下响应:

{locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'arAR'}]}
Run Code Online (Sandbox Code Playgroud)

我想使用 date-fn 库来处理日期格式,但我必须导入整个 date-fn/区域设置,因为我无法事先知道需要哪个区域设置:

import * as dateFnsLocales from 'date-fns/locale';
Run Code Online (Sandbox Code Playgroud)

问题是,某些语言环境的代码格式不同(例如,当后端响应包含代码:“deDE”时启用对德语语言的支持,但相应的 date-fns 包只是“de”。另一方面英语的手 date-fns 包是“enUS”,而不仅仅是“en”。

恕我直言,简单的解决方案是使用一些合并运算符来处理它。示例如下:

import * as dateFnsLocales from 'date-fns/locale';

const supportedLocales = {locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'plPL'}]}
const newArrayWithSupportedLocales = supportedLocales.locales.map((locale) => ({
        ...locale,
        dateFnsLocale: (dateFnsLocales[locale.code] || dateFnsLocales[locale.code.substring(0,2)]),
      }));
Run Code Online (Sandbox Code Playgroud)

不幸的是我收到打字稿错误: No index signature with a parameter of type 'string' was found on type 'typeof import("date-fns/locale")'. TS7053

即使我像这样对尝试进行硬编码:

dateFnsLocale: dateFnsLocales['plPL'.substring(0,2)]
Run Code Online (Sandbox Code Playgroud)

它失败并出现相同的错误,即使这样:

dateFnsLocale: dateFnsLocales['pl']
Run Code Online (Sandbox Code Playgroud)

工作得很好。

Arc*_*ano 14

这是我使用 ExpoLocalization对象进行动态查找的代码。

import * as Localization from 'expo-localization';
import * as Locales from 'date-fns/locale';
import { Locale } from 'date-fns';

/**
 * Looks up a date-fns locale from the Expo localization object.  This falls back to `en-US`
 * @param localization Expo Localization object containing the locale and region.
 * @returns date-fns locale.
 */
export function getDateFnsLocale({ locale, region }: Pick<typeof Localization, 'locale'|'region'>) : Locale {
  return (
    Locales[locale.substring(0, 2) + region] ?? Locales[locale.substring(0, 2)] ?? Locales.enUS
  );
}
Run Code Online (Sandbox Code Playgroud)

这是测试

import { enUS, fr, frCA } from 'date-fns/locale';

describe('date-fns locale lookup', () => {
  it('shound find fr', () => {
    expect(getDateFnsLocale({ locale: 'fr', region: null })).toBe(fr);
  });
  it('shound find fr-CA', () => {
    expect(getDateFnsLocale({ locale: 'fr-CA', region: 'CA' })).toBe(frCA);
  });
  it('shound not find zz-ZZ', () => {
    expect(getDateFnsLocale({ locale: 'zz-ZZ', region: 'ZZ' })).toBe(enUS);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 令人烦恼的是,您需要额外的软件包来解决 date-fns 应该已经提供的问题。谢谢你的解决方案。效果很好! (5认同)
  • 感谢您提供答案和有用的测试! (2认同)