| 18 | }, |
| 19 | |
| 20 | create(context) { |
| 21 | /** |
| 22 | * @param {*} node |
| 23 | */ |
| 24 | function requirePreact(node) { |
| 25 | if (imported) { |
| 26 | return; |
| 27 | } |
| 28 | if (warned) { |
| 29 | return; |
| 30 | } |
| 31 | warned = true; |
| 32 | |
| 33 | const [packageName = '#preact'] = context.options; |
| 34 | |
| 35 | context.report({ |
| 36 | node, |
| 37 | message: [ |
| 38 | 'Using JSX requires importing the Preact namespace', |
| 39 | `Eg, \`import * as Preact from '${packageName}'\``, |
| 40 | ].join('\n\t'), |
| 41 | |
| 42 | fix(fixer) { |
| 43 | const ancestors = context.getAncestors(); |
| 44 | const program = ancestors[0]; |
| 45 | let firstImport = program.body.find( |
| 46 | (node) => node.type === 'ImportDeclaration' |
| 47 | ); |
| 48 | if (!firstImport) { |
| 49 | firstImport = ancestors[1]; |
| 50 | } |
| 51 | |
| 52 | return fixer.insertTextBefore( |
| 53 | firstImport, |
| 54 | `import * as Preact from '${packageName}';\n` |
| 55 | ); |
| 56 | }, |
| 57 | }); |
| 58 | } |
| 59 | |
| 60 | let imported = false; |
| 61 | let warned = false; |
| 62 | |
| 63 | return { |
| 64 | Program() { |
| 65 | imported = false; |
| 66 | warned = false; |
| 67 | }, |
| 68 | |
| 69 | ImportNamespaceSpecifier(node) { |
| 70 | if (node.local.name === 'Preact') { |
| 71 | imported = true; |
| 72 | } |
| 73 | }, |
| 74 | |
| 75 | JSXElement(node) { |
| 76 | requirePreact(node); |
| 77 | }, |