jsx-no-comment-textnodes.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @fileoverview Comments inside children section of tag should be placed inside braces.
  3. * @author Ben Vinegar
  4. */
  5. 'use strict';
  6. const docsUrl = require('../util/docsUrl');
  7. const getText = require('../util/eslint').getText;
  8. const report = require('../util/report');
  9. // ------------------------------------------------------------------------------
  10. // Rule Definition
  11. // ------------------------------------------------------------------------------
  12. const messages = {
  13. putCommentInBraces: 'Comments inside children section of tag should be placed inside braces',
  14. };
  15. /**
  16. * @param {Context} context
  17. * @param {ASTNode} node
  18. * @returns {void}
  19. */
  20. function checkText(context, node) {
  21. // since babel-eslint has the wrong node.raw, we'll get the source text
  22. const rawValue = getText(context, node);
  23. if (/^\s*\/(\/|\*)/m.test(rawValue)) {
  24. // inside component, e.g. <div>literal</div>
  25. if (
  26. node.parent.type !== 'JSXAttribute'
  27. && node.parent.type !== 'JSXExpressionContainer'
  28. && node.parent.type.indexOf('JSX') !== -1
  29. ) {
  30. report(context, messages.putCommentInBraces, 'putCommentInBraces', {
  31. node,
  32. });
  33. }
  34. }
  35. }
  36. /** @type {import('eslint').Rule.RuleModule} */
  37. module.exports = {
  38. meta: {
  39. docs: {
  40. description: 'Disallow comments from being inserted as text nodes',
  41. category: 'Possible Errors',
  42. recommended: true,
  43. url: docsUrl('jsx-no-comment-textnodes'),
  44. },
  45. messages,
  46. schema: [],
  47. },
  48. create(context) {
  49. // --------------------------------------------------------------------------
  50. // Public
  51. // --------------------------------------------------------------------------
  52. return {
  53. Literal(node) {
  54. checkText(context, node);
  55. },
  56. JSXText(node) {
  57. checkText(context, node);
  58. },
  59. };
  60. },
  61. };