no-template-literals.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @author Toru Nagashima <https://github.com/mysticatea>
  3. * See LICENSE file in root directory for full license.
  4. */
  5. "use strict"
  6. /**
  7. * Checks whether it is string literal
  8. * @param {string} s string source code
  9. * @returns {boolean} true: is string literal source code
  10. */
  11. function isStringLiteralCode(s) {
  12. return (
  13. (s.startsWith("'") && s.endsWith("'")) ||
  14. (s.startsWith('"') && s.endsWith('"'))
  15. )
  16. }
  17. /**
  18. * Transform template literal to string concatenation.
  19. * @param {ASTNode} node TemplateLiteral node.(not within TaggedTemplateExpression)
  20. * @param {SourceCode} sourceCode SourceCode
  21. * @returns {string} After transformation
  22. */
  23. function templateLiteralToStringConcat(node, sourceCode) {
  24. const ss = []
  25. node.quasis.forEach((q, i) => {
  26. const value = q.value.cooked
  27. if (value) {
  28. ss.push(JSON.stringify(value))
  29. }
  30. if (i < node.expressions.length) {
  31. const e = node.expressions[i]
  32. const text = sourceCode.getText(e)
  33. ss.push(text)
  34. }
  35. })
  36. if (!ss.length || !isStringLiteralCode(ss[0])) {
  37. ss.unshift(`""`)
  38. }
  39. return ss.join("+")
  40. }
  41. module.exports = {
  42. meta: {
  43. docs: {
  44. description: "disallow template literals.",
  45. category: "ES2015",
  46. recommended: false,
  47. url:
  48. "http://mysticatea.github.io/eslint-plugin-es/rules/no-template-literals.html",
  49. },
  50. fixable: "code",
  51. schema: [],
  52. messages: {
  53. forbidden: "ES2015 template literals are forbidden.",
  54. },
  55. },
  56. create(context) {
  57. const sourceCode = context.getSourceCode()
  58. return {
  59. "TaggedTemplateExpression, :not(TaggedTemplateExpression) > TemplateLiteral"(
  60. node
  61. ) {
  62. context.report({
  63. node,
  64. messageId: "forbidden",
  65. fix:
  66. node.type === "TemplateLiteral"
  67. ? fixer =>
  68. fixer.replaceText(
  69. node,
  70. templateLiteralToStringConcat(
  71. node,
  72. sourceCode
  73. )
  74. )
  75. : undefined,
  76. })
  77. },
  78. }
  79. },
  80. }