pragma.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * @fileoverview Utility functions for React pragma configuration
  3. * @author Yannick Croissant
  4. */
  5. 'use strict';
  6. const JSX_ANNOTATION_REGEX = /^\*\s*@jsx\s+([^\s]+)/;
  7. // Does not check for reserved keywords or unicode characters
  8. const JS_IDENTIFIER_REGEX = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/;
  9. function getCreateClassFromContext(context) {
  10. let pragma = 'createReactClass';
  11. // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  12. if (context.settings.react && context.settings.react.createClass) {
  13. pragma = context.settings.react.createClass;
  14. }
  15. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  16. throw new Error(`createClass pragma ${pragma} is not a valid function name`);
  17. }
  18. return pragma;
  19. }
  20. function getFromContext(context) {
  21. let pragma = 'React';
  22. const sourceCode = context.getSourceCode();
  23. const pragmaNode = sourceCode.getAllComments().find(node => JSX_ANNOTATION_REGEX.test(node.value));
  24. if (pragmaNode) {
  25. const matches = JSX_ANNOTATION_REGEX.exec(pragmaNode.value);
  26. pragma = matches[1].split('.')[0];
  27. // .eslintrc shared settings (http://eslint.org/docs/user-guide/configuring#adding-shared-settings)
  28. } else if (context.settings.react && context.settings.react.pragma) {
  29. pragma = context.settings.react.pragma;
  30. }
  31. if (!JS_IDENTIFIER_REGEX.test(pragma)) {
  32. throw new Error(`React pragma ${pragma} is not a valid identifier`);
  33. }
  34. return pragma;
  35. }
  36. module.exports = {
  37. getCreateClassFromContext: getCreateClassFromContext,
  38. getFromContext: getFromContext
  39. };