no-template-literals.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. messages: {
  52. forbidden: "ES2015 template literals are forbidden.",
  53. },
  54. schema: [],
  55. type: "problem",
  56. },
  57. create(context) {
  58. const sourceCode = context.getSourceCode()
  59. return {
  60. "TaggedTemplateExpression, :not(TaggedTemplateExpression) > TemplateLiteral"(
  61. node
  62. ) {
  63. context.report({
  64. node,
  65. messageId: "forbidden",
  66. fix:
  67. node.type === "TemplateLiteral"
  68. ? fixer =>
  69. fixer.replaceText(
  70. node,
  71. templateLiteralToStringConcat(
  72. node,
  73. sourceCode
  74. )
  75. )
  76. : undefined,
  77. })
  78. },
  79. }
  80. },
  81. }