diff --git a/lib/node-loader-babel.js b/lib/node-loader-babel.js index e41a59b..b268b39 100644 --- a/lib/node-loader-babel.js +++ b/lib/node-loader-babel.js @@ -19,7 +19,15 @@ function isBabelConfigFile(filename) { export async function load(url, context, defaultLoad) { if (useLoader(url)) { - const { source } = await defaultLoad(url, context, defaultLoad); + const { source, format } = await defaultLoad(url, context, defaultLoad); + + // Skip transpilation of CommonJS modules. + // These modules are already preprocessed by Node.js, + // so we cannot parse the non-standard syntaxes like JSX and TypeScript. + // Their transpilation is better handled separately by @babel/register or @babel/node. + if (format !== "module") { + return { source, format }; + } const filename = urlModule.fileURLToPath(url); // Babel config files can themselves be ES modules, @@ -27,7 +35,7 @@ export async function load(url, context, defaultLoad) { if (isBabelConfigFile(filename)) { return { source, - format: /\.(c|m)?js$/.test(filename) ? "module" : "json", + format, }; } @@ -43,9 +51,9 @@ export async function load(url, context, defaultLoad) { return { source: transformed.code, - // Maybe a shaky assumption - // TODO: look at babel config to see whether it will output ESM/CJS or other formats - format: "module", + // NOTE: transform-modules-commonjs doesn't work properly. + // We put a branch here just for consistency. + format: transformed.sourceType === "module" ? "module" : "commonjs", }; } else { return defaultLoad(url, context, defaultLoad); diff --git a/test/basic.test.js b/test/basic.test.js index 930709a..6591008 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -10,6 +10,13 @@ describe(`basic babel usage`, () => { }); }); + it(`allows loading CJS modules`, async () => { + const example = await import("./fixtures/basic/cjs.cjs"); + assert.deepEqual(example.default, { + cjs: "cjs", + }); + }); + it(`supports ES module babel config files`, async () => { const mjsConfig = await import("./fixtures/mjs-config/main.js"); assert.deepEqual(mjsConfig.default, { diff --git a/test/fixtures/basic/cjs.cjs b/test/fixtures/basic/cjs.cjs new file mode 100644 index 0000000..89d0db6 --- /dev/null +++ b/test/fixtures/basic/cjs.cjs @@ -0,0 +1 @@ +exports.cjs = "cjs";