|
| 1 | +import { fileURLToPath } from 'node:url'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { transformAsync } from '@babel/core'; |
| 4 | + |
| 5 | +export function createEsbuildPlugin() { |
| 6 | + const pending = new Map(); |
| 7 | + const cache = new Map(); |
| 8 | + const __dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 9 | + const projectRoot = path.resolve(__dirname, '..'); |
| 10 | + |
| 11 | + return { |
| 12 | + name: 'react-transform', |
| 13 | + enforce: 'pre', |
| 14 | + async transform(code, id) { |
| 15 | + if (id.includes("node_modules") || |
| 16 | + (!id.includes("packages/react/test/shared") && |
| 17 | + !id.includes("packages/react/runtime/test"))) { |
| 18 | + return null; |
| 19 | + } |
| 20 | + |
| 21 | + if (!id.endsWith('.js') && !id.endsWith('.ts') && !id.endsWith('.jsx') && !id.endsWith('.tsx')) { |
| 22 | + return null; |
| 23 | + } |
| 24 | + |
| 25 | + const cached = cache.get(id); |
| 26 | + |
| 27 | + if (cached && cached.input === code) { |
| 28 | + return { |
| 29 | + code: cached.result, |
| 30 | + map: null, |
| 31 | + }; |
| 32 | + } |
| 33 | + |
| 34 | + let result = code; |
| 35 | + |
| 36 | + if (!pending.has(id)) { |
| 37 | + pending.set(id, []); |
| 38 | + |
| 39 | + const jsx = [ |
| 40 | + "@babel/preset-react", |
| 41 | + { |
| 42 | + runtime: "classic", |
| 43 | + pragma: "createElement", |
| 44 | + pragmaFrag: "Fragment", |
| 45 | + }, |
| 46 | + ]; |
| 47 | + |
| 48 | + const ts = [ |
| 49 | + "@babel/preset-typescript", |
| 50 | + { |
| 51 | + jsxPragma: "createElement", |
| 52 | + jsxPragmaFrag: "Fragment", |
| 53 | + }, |
| 54 | + ]; |
| 55 | + |
| 56 | + const transformPath = path.join(projectRoot, "packages/react-transform"); |
| 57 | + const signalsTransform = [ |
| 58 | + transformPath, |
| 59 | + { |
| 60 | + mode: "auto", |
| 61 | + }, |
| 62 | + ]; |
| 63 | + |
| 64 | + const tmp = await transformAsync(result, { |
| 65 | + filename: id, |
| 66 | + sourceMaps: "inline", |
| 67 | + presets: [ts, jsx], |
| 68 | + plugins: [ |
| 69 | + signalsTransform, |
| 70 | + ], |
| 71 | + }); |
| 72 | + result = (tmp && tmp.code) || result; |
| 73 | + cache.set(id, { input: code, result }); |
| 74 | + |
| 75 | + const waited = pending.get(id); |
| 76 | + pending.delete(id); |
| 77 | + waited.forEach(fn => fn()); |
| 78 | + } else { |
| 79 | + await new Promise(r => { |
| 80 | + pending.get(id).push(r); |
| 81 | + }); |
| 82 | + result = cache.get(id).result; |
| 83 | + } |
| 84 | + |
| 85 | + return { |
| 86 | + code: result, |
| 87 | + // TODO (43081j): will this mess sourcemaps up in tests? |
| 88 | + map: null, |
| 89 | + }; |
| 90 | + } |
| 91 | + }; |
| 92 | +} |
0 commit comments