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

CommonJS模块下如何动态获取对应国家的类实例?

解决方案

针对你在module: CommonJS、target: ES2021配置下的问题,有几个可行的解决办法:

1. 用CommonJS的require同步动态加载

因为当前模块系统是CommonJS,直接用require就能实现动态路径加载,无需异步处理:

function getCountryInstance(country: string) {
  // 路径根据项目实际结构调整,确保能定位到对应文件夹
  const { country: countryObj } = require(`./${country}/index.ts`);
  return countryObj;
}

// 调用示例
const canadaInstance = getCountryInstance('canada');

这个方法完全适配现有ES配置,同步执行无需额外异步逻辑。

2. 把动态导入封装到异步函数内

如果偏好ES模块的导入语法,可将动态导入放在async函数中,避开顶级await的限制:

async function getCountryInstance(country: string) {
  const { country: countryObj } = await import(`./${country}/index.ts`);
  return countryObj;
}

// 调用时需通过async/await或.then处理异步
async function run() {
  const englandInstance = await getCountryInstance('england');
  // 后续业务逻辑...
}

run();

3. 预加载所有国家模块(适合国家数量固定且不多的场景)

如果你的国家列表是固定的,可以提前导入所有模块并构建映射表,运行时直接取值:

// 提前导入所有国家实例
import { country as canada } from './canada/index.ts';
import { country as england } from './england/index.ts';
import { country as spain } from './spain/index.ts';

const countryMap = {
  canada,
  england,
  spain
};

function getCountryInstance(country: string) {
  return countryMap[country as keyof typeof countryMap];
}

// 调用示例
const spainInstance = getCountryInstance('spain');

这种方式没有动态加载开销,性能最优,适合国家数量较少的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:40:02