簡體   English   中英

如何創建標記模板文字並將參數傳遞給另一個標記模板文字?

[英]How to create a tagged template literal and pass argument to another tagged template literal?

假設我有

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

但是使用擴展運算符調用它會引發此錯誤。

您可以使用... spread 語法將數組轉換為 arguments 列表以調用highlight

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

看起來 chalk_1.default.apply 是來自您正在使用的轉譯器而不是您的代碼的錯誤。

這是從標記的模板文字修改 output 的示例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM