NodeJS 如何计算字符串以使其成为TS导入路径?

rvpgvaaj  于 2023-05-06  发布在  Node.js
关注(0)|答案(2)|浏览(113)

考虑下面的简单函数:

import * as fr_index from "../locales/index/fr.json"

export const translate = (key: string, from: string) => {

  console.log(fr_index.greeting)   // hello world

  console.log(from)                // fr_index
  console.log(key)                 // greeting
  console.log(from.key)            // undefined <-- Problem
  console.log(from[key])           // undefined <-- Problem
}

如何计算from.key以显示hello world
我试过使用path和/或eval(),但没有成功。谢谢

pgpifvop

pgpifvop1#

下面的功能可以工作,但看起来很丑。

import * as fr_index from '../locales/index/fr.json'
import * as en_index from '../locales/index/en.json'
import * as de_index from '../locales/index/de.json'
import * as it_index from '../locales/index/it.json'
... all i18n files

export const translate = (key: string, from: string) => {
  fr_index; en_index; de_index; it_index   // mandatory
  return eval(from)[key]
}
dffbzjpn

dffbzjpn2#

import * as fr_index from '../locales/index/fr.json'
import * as en_index from '../locales/index/en.json'
import * as de_index from '../locales/index/de.json'
import * as it_index from '../locales/index/it.json'

const DataSheet = {
  fr_index,
  en_index,
  de_index,
  it_index,
} as const

export const translate = <F extends keyof typeof DataSheet, K extends keyof typeof DataSheet[F]>(
    from: F, key: K
) => {
    return DataSheet[from][key]
}
let s = translate('fr_index', 'greeting')
//  ^?
// let s: "hello world"

相关问题