【问题标题】:How to create a tagged template literal and pass argument to another tagged template literal?如何创建标记模板文字并将参数传递给另一个标记模板文字?
【发布时间】:2023-03-12 20:43:01
【问题描述】:

假设我有

const highlight = (strings, ...values) => {
 // console.logs in highlight
}

假设我想创建一个修改模板然后调用 highlight 的“中间件”:

const doMore = (string, ...values) => {
 // modify string/values and then call highlight here
}

所以我现在可以做类似的事情

doMore`
the string ${template}
`;

我不知道如何从doMore 调用highlight。我该怎么做?

我的第一次尝试是使用... 运算符。但这没有用。具体来说,我正在尝试为 npm chalk 应用程序创建一个包装器,所以我做了类似的事情:

const doMore = (string, ...values) => {
 // extend string, values
 return chalk(string, ...values)
}

但这会引发错误:chalk_1.default.apply is not a function。正常做

chalk`the string ${template}`

但使用扩展运算符调用它会引发此错误。

【问题讨论】:

  • function doMore(string, ...values){ const a = [...arguments]; highlight(a.shift(), a); }

标签: javascript tagged-templates


【解决方案1】:

您可以使用... 扩展语法将数组转换为参数列表以调用highlight:

const doMore = (string, ...values) => {
    string += " foo";
    values = values.map(v => v + " bar");
    return highlight(string, ...values);
};

【讨论】:

  • 是的,我确实尝试过 - 我更新了我的评论。我实际上正在尝试为chalk 创建一个包装器,但这不起作用
【解决方案2】:

看起来 chalk_1.default.apply 是来自您正在使用的转译器而不是您的代码的错误。

这是一个修改标记模板文字的输出的示例。

const doMore = (template, ...values) => {
    /**
     * Make sure the template array is the same length as template.raw
     */
    /** Add START on the first line. */
    template[0] = "START" + template[0];
    template.raw[0] = "START" + template.raw[0];
    /** Add END on the last line. */
    template[template.length - 1] =
        template[template.length - 1] + "\nEND";
    template.raw[template.raw.length - 1] =
        template.raw[template.raw.length - 1] + "\\nEND";
    return chalk(template, values);
};
console.log(doMore`
{red This text is shown in red.}
${"This text is inserted."}
{green This text is shown in green.}`);

输出:

START
This text is shown in red.
This text is inserted.
This text is shown in green.
END

【讨论】:

    猜你喜欢
    • 2017-12-03
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2012-02-02
    • 2018-03-13
    • 2019-08-25
    • 2012-07-13
    相关资源
    最近更新 更多