如何在ES6中嵌套模板字符串? [英] How to nest template strings in ES6?
问题描述
我从eslint得到一个 prefer-template
错误。对于解决方法,我更改了我的代码,使用嵌套在 url
函数内的 require
函数中使用模板字符串如下:
I got an prefer-template
error from eslint. For the workaround, I changed my code to use a template string inside the require
function which is nested inside the url
function as following:
{
background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png` center no-repeat`)})
}
但是,这显示出错误。这是我之前使用的代码,在要求
函数之间加上一个加号,而不是模板字符串。
However, that gave an error, obviously. Here is the code I was using before, a plus sign concatenating inside the require
function instead of the template string.
{
background: `url(${require('../../assets/' + edge.node.name.toLowerCase() + '.png')}) center no-repeat`
}
是否可以定义嵌套模板字符串?
Would it be possible to define nested template strings?
推荐答案
是的,这是可能的,但是你有一些原因放在)})
部分(关闭 require
调用,内插值和CSS url
)在错误的地方:
Yes, it's possible, but you had for some reason put the )})
part (that closes the require
call, the interpolated value, and the CSS url
) in the wrong place:
{
background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png`)}) center no-repeat`
// ^^^
}
说,这可能是一个坏主意,因为它不能使代码可读。更好地使用变量:
That said, it's probably a bad idea as it doesn't exactly make the code readable. Better use a variable:
const bgurl = require(`../../assets/${edge.node.name.toLowerCase()}.png`);
… {
background: `url(${bgurl}) center no-repeat`
}
这篇关于如何在ES6中嵌套模板字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!