31

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
lvarayut
  • 13,963
  • 17
  • 63
  • 87

1 Answers1

40

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`
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thanks for your response. That was my mistake for the demo. However, when I changed it to `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png`)) center no-repeat` It's a syntax error. – lvarayut Mar 16 '16 at 07:52
  • @LVarayut: [Worksforme](http://babeljs.io/repl/#?evaluate=true&presets=es2015&code=const%20x%20%3D%20{%0A%20%20background%3A%20%60url%28%24{require%28%60..%2F..%2Fassets%2F%24{edge.node.name.toLowerCase%28%29}.png%60%29}%29%20center%20no-repeat%60%0A}%3B). What error exactly are you getting? – Bergi Mar 16 '16 at 07:57
  • 1
    Thanks @Bergi. Was my confusion about curly brackets. BTW, I'll go with your second approach. – lvarayut Mar 16 '16 at 08:05