sindresorhus / eslint-plugin-unicorn

More than 100 powerful ESLint rules
MIT License
4.31k stars 365 forks source link

Create a better `prefer-template` rule #78

Open sindresorhus opened 7 years ago

sindresorhus commented 7 years ago

As usual the built-in one is flawed and as usual the ESLint team refuses to acknowledge that. Luckily we can just build something better. Ref: https://github.com/eslint/eslint/issues/6572#issuecomment-229927387

jfmengels commented 7 years ago

I think it's too bad to limit this rule to only work for identifiers, but I agree that the core is too forceful at times. What do you think about looking at the length of the expression and report when using expressions (that are more complex than just a single variable) that use less than X characters (10, 15, 20?)?

This would result in something like this

Fail

// if limit set at 15, `blue('foo')` takes 11 chars
var foo = red('I') + ' like ' + blue('foo') + ' and ' + foo(a, b);

Pass

var foo = chalk.red('I') + ' like ' + chalk.blue('unicorns') + ' and ' + chalk.yellow('ponies');

I'm fine with this rule, but would love it if stuff like 'prefix' + format(a, b) would be reported, as I'd prefer a template to be used here.

sindresorhus commented 7 years ago

@jfmengels Length is very arbitrary though. I don't see why the above examples should be treated differently. It's not just the length that makes some template literals hard to read. Usually it's more about the complexity of the thing inside the template braces.

We could use multiple heuristics:

Thoughts?

I'm fine with this rule, but would love it if stuff like 'prefix' + format(a, b) would be reported, as I'd prefer a template to be used here.

Me too, but hard to find an automatic balance here. Let's think about it some more.

florianb commented 7 years ago

When trying to recognize string assembling expressions it takes me more effort to understand it the more the string is distracted by complexity.

Probably it is possible to estimate the distraction by the proportion of plain text to the amount of expressions?

sindresorhus commented 3 years ago

Let's start with this heuristic and we can improve it based on actual usage:

sindresorhus commented 3 years ago

This is now accepted.