Warm tip: This article is reproduced from stackoverflow.com, please click
ecmascript-6 javascript chalk

chalk tagged template literals within strings

发布于 2020-03-29 20:58:35

i am using chalk and i am constructing a string programatically (see str in the snippet below).

i would like chalk to honor my string as it would honor tagged termplate literals.

how can it be done?

const chalk = require('chalk');
const p = chalk`{bold BOLD}`

const str = `{bold BOLD}`
const q = chalk`${str}`

console.log(p == q ? "ok" : "!ok")

as you can see p and q are different - the code always outputs !ok.

Questioner
Mr.
Viewed
44
Mr. 2020-02-02 00:03

i found a proxy for chalk that does just this

const chalk = require("chalk");

const chalkish = (parts, ...substitutions) => {
  const rawResults = [];
  const cookedResults = [];
  for (var i = 0; i < parts.length; i++) {
    rawResults.push(parts.raw[i]);
    cookedResults.push(parts[i]);
    if (i < substitutions.length) {
      rawResults.push(substitutions[i]);
      cookedResults.push(substitutions[i]);
    }
  }

  const chalkParts = [cookedResults.join("")];
  chalkParts.raw = [rawResults.join("")];

  return (chalk(chalkParts));
}