如何在模板字符串文字的变量中写入变量?

时间:2022-08-10 17:08:53

log(`${chalk.magenta('???? LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red('${LAUNCH_COMMAND}')}` );

日志(“$ {粉笔。magenta('????LAUNCH_COMMAND')} ${chalk.绿色(npm运行:)} $ { chalk.red(“$ { LAUNCH_COMMAND }”)}”);

Here is the problem part: ${chalk.red('${LAUNCH_COMMAND}')}

这里是问题部分:${chalk.red('${LAUNCH_COMMAND}')}

LAUNCH_COMMAND is either 'production' or 'development'. However it's inside of another ${}.

LAUNCH_COMMAND要么是“生产”,要么是“开发”。然而,它在另一个${}内。

如何在模板字符串文字的变量中写入变量?

2 个解决方案

#1


3  

Demo

演示

Just use the Variable name for nested Variable in Template String literal

只需在模板字符串文字中使用嵌套变量的变量名

`${chalk.red(LAUNCH_COMMAND)}` // for nested sting literal just use the variable name 

const LAUNCH_COMMAND = 'hi';
console.log(`${chalk.magenta('????  LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red(LAUNCH_COMMAND)}` );

如何在模板字符串文字的变量中写入变量?

#2


-1  

You don't wrap variables within string literals with quotes.

不需要用引号将变量括起来。

log(`${chalk.magenta(????  LAUNCH_COMMAND)} ${chalk.green(npm run: )} ${chalk.red(LAUNCH_COMMAND})` ); 

^ Should hypothetically work though I'm not clear on the context behind why you're writing a string like this. I'm assuming it's some kind of dynamic output.

^应该假设工作虽然我不清楚你为什么背后的背景写这样的字符串。我假设它是某种动态输出。

var b = "Cats"
var c = "Dogs"

function concat(one, two) {

  return `${one} and ${two}`;

}

function compare(one, two) {

  var ans = one == two ? 'Are the same' : 'Are not the same';
  return ans;

}

console.log(`${concat(b, c)} - ${compare(b, c)}`);

#1


3  

Demo

演示

Just use the Variable name for nested Variable in Template String literal

只需在模板字符串文字中使用嵌套变量的变量名

`${chalk.red(LAUNCH_COMMAND)}` // for nested sting literal just use the variable name 

const LAUNCH_COMMAND = 'hi';
console.log(`${chalk.magenta('????  LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red(LAUNCH_COMMAND)}` );

如何在模板字符串文字的变量中写入变量?

#2


-1  

You don't wrap variables within string literals with quotes.

不需要用引号将变量括起来。

log(`${chalk.magenta(????  LAUNCH_COMMAND)} ${chalk.green(npm run: )} ${chalk.red(LAUNCH_COMMAND})` ); 

^ Should hypothetically work though I'm not clear on the context behind why you're writing a string like this. I'm assuming it's some kind of dynamic output.

^应该假设工作虽然我不清楚你为什么背后的背景写这样的字符串。我假设它是某种动态输出。

var b = "Cats"
var c = "Dogs"

function concat(one, two) {

  return `${one} and ${two}`;

}

function compare(one, two) {

  var ans = one == two ? 'Are the same' : 'Are not the same';
  return ans;

}

console.log(`${concat(b, c)} - ${compare(b, c)}`);