You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何封装node-i18n-iso-countries的getName函数以新增国家名称?

优化node-i18n-iso-countries的getName函数,支持自定义国家名称

1. 用自定义映射表封装(推荐,扩展性强)

这种方式替代零散的if-else,新增国家只需在映射表中添加条目,无需修改逻辑代码。TypeScript下还能通过类型定义保证参数和返回值的安全性。

import isoCountries from 'node-i18n-iso-countries';

// 定义多语言自定义国家映射表
// 结构:{ 语言代码: { 国家代码: 自定义名称 } }
const customCountryMap: Record<string, Record<string, string>> = {
  'zh-CN': {
    'XK': '科索沃',
    'ZZ': '我的自定义国家'
  },
  'en': {
    'XK': 'Kosovo',
    'ZZ': 'My Custom Country'
  }
};

// 封装后的getName函数
function getCountryName(code: string, lang: string): string | undefined {
  // 优先读取自定义映射
  const customName = customCountryMap[lang]?.[code];
  if (customName) {
    return customName;
  }
  // 自定义无匹配时,调用原库方法
  return isoCountries.getName(code, lang);
}

// 使用示例
console.log(getCountryName('CN', 'zh-CN')); // 原库返回"中国"
console.log(getCountryName('XK', 'zh-CN')); // 自定义返回"科索沃"

如果仅需单语言自定义,可简化映射表:

const customCountrySingleLang: Record<string, string> = {
  'XK': '科索沃',
  'ZZ': '我的自定义国家'
};

function getCountryNameSingleLang(code: string, lang: string): string | undefined {
  // 使用空值合并运算符简化判断
  return customCountrySingleLang[code] ?? isoCountries.getName(code, lang);
}

2. 扩展原库本地化数据(贴合原库设计)

node-i18n-iso-countries原生支持扩展本地化数据,这种方式能让自定义国家和原库数据无缝融合,所有原库方法(如getNames)都会自动包含自定义条目。

import isoCountries from 'node-i18n-iso-countries';

// 先注册原有的中文本地化数据
isoCountries.registerLocale(require('node-i18n-iso-countries/langs/zh.json'));

// 向中文本地化中添加自定义国家
isoCountries.registerLocale({
  zh: {
    countries: {
      'XK': '科索沃',
      'ZZ': '我的自定义国家'
    }
  }
});

// 直接使用原库getName即可
console.log(isoCountries.getName('XK', 'zh')); // 输出"科索沃"
console.log(isoCountries.getName('US', 'zh')); // 输出"美国"

两种方案对比

  • 映射表封装:灵活可控,不修改原库数据,适合临时添加少量自定义国家
  • 扩展本地化:符合原库设计逻辑,适合长期维护的自定义国家,所有原库方法都能复用

内容的提问来源于stack exchange,提问作者Mhadhbi Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:48:23