【问题标题】:Hot to access detailed variable information in tagged template literals like property name?访问标记模板文字(如属性名称)中的详细变量信息很热门?
【发布时间】:2021-11-26 08:40:33
【问题描述】:

如果我有一个返回标记模板文字的函数,我可以在控制台记录函数 toString(),它会显示我的变量的对象和属性名称。

function myfN() {
 return tag`Test ${data.name}`
}
    
// this console logs the information I would need inside my tag, see below.
console.log(myfN.toString())
console output >>>>
function myfN() {
 return tag(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2["default"])(["Test ", ""])), data.name);
}

如您所见,data.name 在日志结果中,现在当我们查看我的标记函数时,我有我的字符串和值

function tag(literals, ...vars) {
  console.log(literals.raw);
  console.log(vars);

  // get here that the literals are using `data.name`
}

有什么方法可以在不将整个对象作为值传递到字符串的情况下获取我的标签中的变量名称? 一切

【问题讨论】:

    标签: javascript typescript tagged-templates


    【解决方案1】:

    与其他函数一样,您无法访问用于向其中传递数据的变量名。也可能根本没有变量:

    tag`Test ${"look, ma! No variables!"}`
    

    获取变量名(如果有的话)并使用它的唯一方法是解析和操作代码,例如使用 babel。

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多