jsx-quotes.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /**
  2. * @fileoverview A rule to ensure consistent quotes used in jsx syntax.
  3. * @author Mathias Schreck <https://github.com/lo1tuma>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Constants
  12. //------------------------------------------------------------------------------
  13. const QUOTE_SETTINGS = {
  14. "prefer-double": {
  15. quote: "\"",
  16. description: "singlequote",
  17. convert(str) {
  18. return str.replace(/'/g, "\"");
  19. }
  20. },
  21. "prefer-single": {
  22. quote: "'",
  23. description: "doublequote",
  24. convert(str) {
  25. return str.replace(/"/g, "'");
  26. }
  27. }
  28. };
  29. //------------------------------------------------------------------------------
  30. // Rule Definition
  31. //------------------------------------------------------------------------------
  32. module.exports = {
  33. meta: {
  34. docs: {
  35. description: "enforce the consistent use of either double or single quotes in JSX attributes",
  36. category: "Stylistic Issues",
  37. recommended: false,
  38. url: "https://eslint.org/docs/rules/jsx-quotes"
  39. },
  40. fixable: "whitespace",
  41. schema: [
  42. {
  43. enum: ["prefer-single", "prefer-double"]
  44. }
  45. ]
  46. },
  47. create(context) {
  48. const quoteOption = context.options[0] || "prefer-double",
  49. setting = QUOTE_SETTINGS[quoteOption];
  50. /**
  51. * Checks if the given string literal node uses the expected quotes
  52. * @param {ASTNode} node - A string literal node.
  53. * @returns {boolean} Whether or not the string literal used the expected quotes.
  54. * @public
  55. */
  56. function usesExpectedQuotes(node) {
  57. return node.value.indexOf(setting.quote) !== -1 || astUtils.isSurroundedBy(node.raw, setting.quote);
  58. }
  59. return {
  60. JSXAttribute(node) {
  61. const attributeValue = node.value;
  62. if (attributeValue && astUtils.isStringLiteral(attributeValue) && !usesExpectedQuotes(attributeValue)) {
  63. context.report({
  64. node: attributeValue,
  65. message: "Unexpected usage of {{description}}.",
  66. data: {
  67. description: setting.description
  68. },
  69. fix(fixer) {
  70. return fixer.replaceText(attributeValue, setting.convert(attributeValue.raw));
  71. }
  72. });
  73. }
  74. }
  75. };
  76. }
  77. };