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?
Nesting together multiple template literals can create unnecessary complexity, which reduces the code quality. The code becomes less readable and can cause maintainability issues overtime. A better practice, in these situations, is to move the nested template into a separate statement.
Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.
Backticks ( ` ) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier. Features: we can interpolate any kind of expression in the template literals. They can be multi-line.
String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.
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`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With