diff --git a/lib/node-loader-babel.js b/lib/node-loader-babel.js index e41a59b..a90c9ce 100644 --- a/lib/node-loader-babel.js +++ b/lib/node-loader-babel.js @@ -17,9 +17,21 @@ function isBabelConfigFile(filename) { ); } +// The formats that babel can compile +// It cannot compile wasm/json +const supportedModuleFormats = ["module", "commonjs"]; + 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); + + // NodeJS' implementation of defaultLoad returns a source of `null` for CommonJS modules. + // So we just skip compilation when it's commonjs until a future day when NodeJS (might) support that. + // Also, we skip compilation of wasm and json modules by babel, since babel isn't needed or possible + // in those situations + if (!source || (format && !supportedModuleFormats.includes(format))) { + return { source, format }; + } const filename = urlModule.fileURLToPath(url); // Babel config files can themselves be ES modules, @@ -32,7 +44,7 @@ export async function load(url, context, defaultLoad) { } const options = await loadOptionsAsync({ - sourceType: "module", + sourceType: format || "module", root: process.cwd(), rootMode: "root", filename: filename, diff --git a/test/commonjs.test.js b/test/commonjs.test.js new file mode 100644 index 0000000..2878582 --- /dev/null +++ b/test/commonjs.test.js @@ -0,0 +1,15 @@ +import assert from "assert"; + +describe("babel compilation of commonjs files", () => { + it(`can transform commonjs modules`, async () => { + const commonJSModule = await import("./fixtures/commonjs/main.cjs"); + + assert.deepEqual(commonJSModule.default, { + red: "#ff0000", + blue: "#0000ff", + }); + + assert.deepEqual(commonJSModule.red, "#ff0000"); + assert.deepEqual(commonJSModule.blue, "#0000ff"); + }); +}); diff --git a/test/fixtures/commonjs/main.cjs b/test/fixtures/commonjs/main.cjs new file mode 100644 index 0000000..ca47018 --- /dev/null +++ b/test/fixtures/commonjs/main.cjs @@ -0,0 +1,2 @@ +exports.red = "#ff0000"; +exports.blue = "#0000ff"; diff --git a/test/run-tests.js b/test/run-tests.js index fd0a200..645297f 100644 --- a/test/run-tests.js +++ b/test/run-tests.js @@ -3,6 +3,7 @@ import Mocha from "mocha"; const mocha = new Mocha(); mocha.addFile("./test/basic.test.js"); +mocha.addFile("./test/commonjs.test.js"); mocha.loadFilesAsync().then(() => { mocha.run();