/packages/eslint-plugin-patternfly-react/lib/rules/import-tokens-icons.js

https://github.com/patternfly/patternfly-react · JavaScript · 58 lines · 51 code · 2 blank · 5 comment · 5 complexity · ed79327b615797e8b109a8339d2e12c6 MD5 · raw file

  1. /**
  2. * @param specifier module specifier
  3. * @param moduleName module name (@patternfly/react-tokens or @patternfly/react-icons)
  4. * @returns string of non-treeshaken import
  5. */
  6. function makeImport(specifier, moduleName) {
  7. let res = `import ${specifier.local.name} from '`;
  8. res += moduleName.replace(/\/dist\/(js|esm)/, '');
  9. res += '/dist/js';
  10. if (moduleName.includes('icon')) {
  11. res += '/icons/';
  12. res += specifier.imported.name.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`).replace(/^-/, '');
  13. } else {
  14. res += `/${specifier.imported.name}`;
  15. }
  16. res += "';";
  17. return res;
  18. }
  19. module.exports = {
  20. meta: {
  21. docs: {
  22. description: 'Do not rely on ESM treeshaking for icons and tokens',
  23. category: 'Possible Errors',
  24. recommended: true
  25. },
  26. fixable: 'code',
  27. schema: [
  28. {
  29. type: 'object',
  30. properties: {},
  31. additionalProperties: true
  32. }
  33. ]
  34. },
  35. create(context) {
  36. return {
  37. ImportDeclaration(node) {
  38. if (/@patternfly\/react-(tokens|icons)(\/dist\/(js|esm))?/.test(node.source.value)) {
  39. const esmSpecifiers = node.specifiers.filter(specifier => specifier.type === 'ImportSpecifier');
  40. if (esmSpecifiers.length > 0) {
  41. context.report({
  42. node,
  43. message: `Importing from the barrel ${node.source.value} file will blow up CJS bundle sizes. Import directly from dist/js file instead.`,
  44. fix(fixer) {
  45. return fixer.replaceText(
  46. node,
  47. esmSpecifiers.map(spec => makeImport(spec, node.source.value)).join('\n')
  48. );
  49. }
  50. });
  51. }
  52. }
  53. }
  54. };
  55. }
  56. };