How to insert template strings in ES6?

I got a prefer-template error from eslint. For a workaround, I changed my code to use the template string inside the require function, which is nested inside the url function as follows:

 { background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png` center no-repeat`)}) } 

However, this gave an error, obviously. Here is the code I used before, plus the character concatenating inside the require function instead of the template string.

 { background: `url(${require('../../assets/' + edge.node.name.toLowerCase() + '.png')}) center no-repeat` } 

Can I define nested template strings?

+9
javascript ecmascript-6 template-literals
source share
1 answer

Yes, it is possible, but for some reason you put the part )}) (which closes the require call, interpolated value and CSS url ) in the wrong place:

 { background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png`)}) center no-repeat` // ^^^ } 

However, this is probably a bad idea, as it does not make the code readable. Better to use a variable:

 const bgurl = require(`../../assets/${edge.node.name.toLowerCase()}.png`); … { background: `url(${bgurl}) center no-repeat` } 
+14
source share

All Articles