jsx-filename-extension.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @fileoverview Restrict file extensions that may contain JSX
  3. * @author Joe Lencioni
  4. */
  5. 'use strict';
  6. const path = require('path');
  7. const docsUrl = require('../util/docsUrl');
  8. // ------------------------------------------------------------------------------
  9. // Constants
  10. // ------------------------------------------------------------------------------
  11. const DEFAULTS = {
  12. extensions: ['.jsx']
  13. };
  14. // ------------------------------------------------------------------------------
  15. // Rule Definition
  16. // ------------------------------------------------------------------------------
  17. module.exports = {
  18. meta: {
  19. docs: {
  20. description: 'Restrict file extensions that may contain JSX',
  21. category: 'Stylistic Issues',
  22. recommended: false,
  23. url: docsUrl('jsx-filename-extension')
  24. },
  25. schema: [{
  26. type: 'object',
  27. properties: {
  28. extensions: {
  29. type: 'array',
  30. items: {
  31. type: 'string'
  32. }
  33. }
  34. },
  35. additionalProperties: false
  36. }]
  37. },
  38. create: function(context) {
  39. function getExtensionsConfig() {
  40. return context.options[0] && context.options[0].extensions || DEFAULTS.extensions;
  41. }
  42. let invalidExtension;
  43. let invalidNode;
  44. // --------------------------------------------------------------------------
  45. // Public
  46. // --------------------------------------------------------------------------
  47. return {
  48. JSXElement: function(node) {
  49. const filename = context.getFilename();
  50. if (filename === '<text>') {
  51. return;
  52. }
  53. if (invalidNode) {
  54. return;
  55. }
  56. const allowedExtensions = getExtensionsConfig();
  57. const isAllowedExtension = allowedExtensions.some(extension => filename.slice(-extension.length) === extension);
  58. if (isAllowedExtension) {
  59. return;
  60. }
  61. invalidNode = node;
  62. invalidExtension = path.extname(filename);
  63. },
  64. 'Program:exit': function() {
  65. if (!invalidNode) {
  66. return;
  67. }
  68. context.report({
  69. node: invalidNode,
  70. message: `JSX not allowed in files with extension '${invalidExtension}'`
  71. });
  72. }
  73. };
  74. }
  75. };