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

如何将字符串解析为TS导入路径并访问对应模块属性?

问题根源

你传入的from是字符串"fr_index",但这个字符串和你导入的fr_index模块对象完全是两码事——字符串本身没有greeting属性,用from[key]访问的也是字符串的字符位置(字符串索引仅支持数字),自然拿不到模块里的值。

解决方案

方案一:用映射表关联字符串与模块

提前导入所有需要的语言模块,创建一个映射对象把字符串名称和对应模块绑定,通过传入的字符串找到模块后再取值:

import * as fr_index from "../locales/index/fr.json";
import * as en_index from "../locales/index/en.json"; // 示例其他语言模块

// 建立字符串名称到模块的映射
const localeMap = {
  fr_index: fr_index,
  en_index: en_index,
  // 新增语言模块时在这里补充
};

export const translate = (key: string, from: keyof typeof localeMap) => {
  const targetModule = localeMap[from];
  console.log(targetModule[key]); // 现在能正确获取fr_index.greeting的值
};

TypeScript会通过keyof typeof localeMap自动做类型校验,避免传入不存在的模块名称。

方案二:动态导入(按需加载场景)

如果需要根据字符串路径动态加载模块,先在tsconfig.json里开启相关配置:

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    // 其他原有配置...
  }
}

然后把translate改成异步函数,用动态import()加载指定路径的JSON:

export const translate = async (key: string, fromPath: string) => {
  // fromPath是JSON文件相对于当前文件的路径,比如"../locales/index/fr.json"
  const localeModule = await import(fromPath);
  console.log(localeModule.default[key]); // 动态导入JSON时,默认导出是整个JSON对象
};

调用时直接传入路径字符串即可:

translate("greeting", "../locales/index/fr.json");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 02:37:15