我创建了一个类来处理我的通知。为了更改文本颜色,我使用的包接受以下内容:
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}}`
});
gulp-include/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();
我该如何解决这个问题?
最佳答案
要使chalk
解析Log
类中的字符串模板,需要模拟tagged template literals手动 -- 自己编写标签函数调用。
幸运的是,在这种情况下,字符串模板中的 ${test}
等表达式在第一次出现时就已经被求值了。所以传递给 chalk
的唯一参数是解析了一半的字符串,例如'{red 此文本将被读取。 helloworld}'
(${params.message}
的值),这让事情变得简单多了。
在Log
类中,可以通过以下方法模拟chalk
标记的模板字面量:
log(params) {
let message = params.message;
let options = [message];
options.raw = [message];
log(chalk(options));
}
关于javascript - gulp chalk,通过方法传递字符串模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526522/