Search code examples
javascriptecmascript-6chalk

chalk tagged template literals within strings


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.


Solution

  • 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));
    }