| 1 | import babel from '@babel/core'; |
| 2 | |
| 3 | const babelOptions = { |
| 4 | babelrc: false, |
| 5 | ignore: [/\/(build|node_modules)\//], |
| 6 | plugins: [ |
| 7 | '@babel/plugin-syntax-import-meta', |
| 8 | '@babel/plugin-transform-react-jsx', |
| 9 | ], |
| 10 | }; |
| 11 | |
| 12 | export async function load(url, context, defaultLoad) { |
| 13 | if (url.endsWith('.css')) { |
| 14 | return {source: 'export default {}', format: 'module', shortCircuit: true}; |
| 15 | } |
| 16 | const {format} = context; |
| 17 | const result = await defaultLoad(url, context, defaultLoad); |
| 18 | if (result.format === 'module') { |
| 19 | const opt = Object.assign({filename: url}, babelOptions); |
| 20 | const newResult = await babel.transformAsync(result.source, opt); |
| 21 | if (!newResult) { |
| 22 | if (typeof result.source === 'string') { |
| 23 | return result; |
| 24 | } |
| 25 | return { |
| 26 | source: Buffer.from(result.source).toString('utf8'), |
| 27 | format: 'module', |
| 28 | }; |
| 29 | } |
| 30 | return {source: newResult.code, format: 'module'}; |
| 31 | } |
| 32 | return defaultLoad(url, context, defaultLoad); |
| 33 | } |
| 34 | |
| 35 | async function babelTransformSource(source, context, defaultTransformSource) { |
| 36 | const {format} = context; |
| 37 | if (format === 'module') { |
| 38 | const opt = Object.assign({filename: context.url}, babelOptions); |
| 39 | const newResult = await babel.transformAsync(source, opt); |
| 40 | if (!newResult) { |
| 41 | if (typeof source === 'string') { |
| 42 | return {source}; |
| 43 | } |
| 44 | return { |
| 45 | source: Buffer.from(source).toString('utf8'), |
| 46 | }; |
| 47 | } |
| 48 | return {source: newResult.code}; |
| 49 | } |
| 50 | return defaultTransformSource(source, context, defaultTransformSource); |
| 51 | } |
| 52 | |
| 53 | export const transformSource = |
| 54 | process.version < 'v16' ? babelTransformSource : undefined; |