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.   const {format} = context;
    
  14.   const result = await defaultLoad(url, context, defaultLoad);
    
  15.   if (result.format === 'module') {
    
  16.     const opt = Object.assign({filename: url}, babelOptions);
    
  17.     const newResult = await babel.transformAsync(result.source, opt);
    
  18.     if (!newResult) {
    
  19.       if (typeof result.source === 'string') {
    
  20.         return result;
    
  21.       }
    
  22.       return {
    
  23.         source: Buffer.from(result.source).toString('utf8'),
    
  24.         format: 'module',
    
  25.       };
    
  26.     }
    
  27.     return {source: newResult.code, format: 'module'};
    
  28.   }
    
  29.   return defaultLoad(url, context, defaultLoad);
    
  30. }
    
  31. 
    
  32. async function babelTransformSource(source, context, defaultTransformSource) {
    
  33.   const {format} = context;
    
  34.   if (format === 'module') {
    
  35.     const opt = Object.assign({filename: context.url}, babelOptions);
    
  36.     const newResult = await babel.transformAsync(source, opt);
    
  37.     if (!newResult) {
    
  38.       if (typeof source === 'string') {
    
  39.         return {source};
    
  40.       }
    
  41.       return {
    
  42.         source: Buffer.from(source).toString('utf8'),
    
  43.       };
    
  44.     }
    
  45.     return {source: newResult.code};
    
  46.   }
    
  47.   return defaultTransformSource(source, context, defaultTransformSource);
    
  48. }
    
  49. 
    
  50. export const transformSource =
    
  51.   process.version < 'v16' ? babelTransformSource : undefined;