Javascript 吞下粉笔,通过方法传递字符串模板

Javascript 吞下粉笔,通过方法传递字符串模板,javascript,node.js,Javascript,Node.js,我已经创建了一个类来处理我的通知。为了更改文本颜色,我使用的软件包接受以下内容: const chalk = require('chalk'); chalk`{red This text will be red.}`; 然而,我现在已经将这个字符串模板传递到了一个方法中,然后该方法将它传递给了chalk,但是chalk包没有解析字符串模板。因此,日志只是显示传入的字符串,而不是更改颜色 const log = require('./gulp-includes/log'); let test

我已经创建了一个类来处理我的通知。为了更改文本颜色,我使用的软件包接受以下内容:

const chalk = require('chalk');

chalk`{red This text will be red.}`;
然而,我现在已经将这个字符串模板传递到了一个方法中,然后该方法将它传递给了chalk,但是chalk包没有解析字符串模板。因此,日志只是显示传入的字符串,而不是更改颜色

const log = require('./gulp-includes/log');

let test = 'helloworld';
log.all({
    message: `{red This text will be read. ${test}}`
});
大口吞下包含/log.js

const settings = require('./settings.js');
const chalk = require('chalk');
const log = require('fancy-log');
const notifier = require('node-notifier');

class Log
{
    all(params) {
        this.log(params);
    }
    log(params) {
        log(chalk`${params.message}`);
    }

}
module.exports = new Log();

如何解决此问题?

要在
Log
类中制作
chalk
解析字符串模板,您需要模拟手动-编写标记函数调用自己

幸运的是,在这种情况下,字符串模板中的表达式(如
${test}
)在第一次出现时就已经被计算过了。因此,传递给
粉笔的唯一参数是半解析字符串,例如
{red This text will be read.helloworld}
(值
${params.message}
),这使事情变得更简单

Log
类中,可以通过以下方法模拟
chalk
标记的模板文字:

log(params) {
  let message = params.message;
  let options = [message];
  options.raw = [message];
  log(chalk(options));
}

我被认为必须这样做,但我一生都无法从代码或文档中找到答案。谢谢