1

假设我有

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}
`;

我不知道如何highlightdoMore. 我该怎么做呢?

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

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

但这会引发错误:chalk_1.default.apply is not a function. 平时做

chalk`the string ${template}`

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

4

2 回答 2

0

It looks like chalk_1.default.apply is an error from the transpiler that you are using rather than your code.

Here is an example of modifying the output from the tagged template literal.

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.}`);

Outputs:

START
This text is shown in red.
This text is inserted.
This text is shown in green.
END
于 2020-07-16T01:22:34.313 回答
0

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

const doMore = (string, ...values) => {
    string += " foo";
    values = values.map(v => v + " bar");
    return highlight(string, ...values);
};
于 2020-06-30T00:25:03.423 回答