Skip to content

Instantly share code, notes, and snippets.

@olegpolyakov
Created January 13, 2023 04:27
Show Gist options
  • Save olegpolyakov/a9c10d7b4767a3846f08dab3bc74d4a3 to your computer and use it in GitHub Desktop.
Save olegpolyakov/a9c10d7b4767a3846f08dab3bc74d4a3 to your computer and use it in GitHub Desktop.
Node JSX Loader
import { pathToFileURL } from 'url';
import { transformAsync } from '@babel/core';
const baseURL = pathToFileURL(`${process.cwd()}/`).href;
const extensionsRegex = /\.jsx$/;
const supportedModuleFormats = ['module', 'commonjs'];
const babelOptions = {
presets: [
['@babel/preset-react']
]
};
export async function resolve(specifier, context, nextResolve) {
if (extensionsRegex.test(specifier)) {
const { parentURL = baseURL } = context;
// Node.js normally errors on unknown file extensions, so return a URL for
// specifiers ending in the CoffeeScript file extensions.
return {
shortCircuit: true,
format: 'module',
url: new URL(specifier, parentURL).href
};
} else {
return nextResolve(specifier);
}
}
export async function load(url, context, nextLoad) {
if (!/node_modules/.test(url) && !/node:/.test(url)) {
const { source, format } = await nextLoad(url, context, nextLoad);
if (!source || (format && !supportedModuleFormats.includes(format))) {
return { source, format };
}
const result = await transformAsync(source, babelOptions);
return {
source: result.code,
format: 'module'
};
} else {
return nextLoad(url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment