no-override-exports.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const path = require('path');
  3. const utils = require('../utils');
  4. module.exports = {
  5. meta: {
  6. docs: {
  7. description: 'Disallow override exports',
  8. category: 'Possible Errors',
  9. recommended: true,
  10. url: 'https://github.com/eggjs/eslint-plugin-eggache#no-override-exports',
  11. },
  12. schema: [
  13. {
  14. // if true, check all file, otherwise only check `config/config.*.js` or config/plugin.*.js`
  15. type: 'boolean',
  16. },
  17. ],
  18. messages: {
  19. overrideExports: 'Don\'t overide `exports`',
  20. overrideModule: 'Don\'t overide `module.exports`',
  21. },
  22. },
  23. create(context) {
  24. let hasExports = false;
  25. let hasModule = false;
  26. const shouldCheckAll = context.options[0];
  27. // if `!shouldCheckAll`, then only check `<input>` or `config/config.*.js` or `config/plugin.*.js`
  28. if (!shouldCheckAll && !isConfig(context)) return {};
  29. return {
  30. ExpressionStatement(node) {
  31. // only consider the root scope
  32. if (!node.parent || node.parent.type !== 'Program') return;
  33. if (node.expression.type !== 'AssignmentExpression') return;
  34. const testNode = node.expression.left;
  35. if (utils.isExports(testNode)) {
  36. if (hasModule) {
  37. context.report({ node, messageId: 'overrideExports' });
  38. }
  39. hasExports = true;
  40. } else if (utils.isModule(testNode)) {
  41. if (hasExports) {
  42. context.report({ node, messageId: 'overrideExports' });
  43. }
  44. if (hasModule) {
  45. context.report({ node, messageId: 'overrideModule' });
  46. }
  47. hasModule = true;
  48. }
  49. },
  50. };
  51. },
  52. };
  53. function isConfig(context) {
  54. const filePath = context.getFilename();
  55. if (filePath === '<input>') return true;
  56. const baseName = path.basename(filePath);
  57. const dirname = path.basename(path.dirname(filePath));
  58. return dirname === 'config' && (baseName.startsWith('config.') || baseName.startsWith('plugin.'));
  59. }