Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mixed-format/fixture/cjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
exports.qux = require('./cjs2.js');
1 change: 1 addition & 0 deletions mixed-format/fixture/cjs2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = 'zed';
1 change: 1 addition & 0 deletions mixed-format/fixture/esm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const foo = 'bar';
3 changes: 3 additions & 0 deletions mixed-format/fixture/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "commonjs"
}
34 changes: 34 additions & 0 deletions mixed-format/loader.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export async function load(url, context, nextLoad) {
if (!url.endsWith('.js')) return nextLoad(url);

const nextResult = await nextLoad(url, { ...context, format: 'module' })
.then((result) => {
if (containsCJS(result.source)) { throw new Error('CommonJS'); }

return result;
})
.catch(async (err) => {
if (
(err?.message.includes('require') && err.includes('import'))
|| err?.message.includes('CommonJS')
) {
return { format: 'commonjs' };
}

throw err;
});

return nextResult;
}

function containsCJS(source) {
const src = '' + source;

// A realistic version of this loader would use a parser like Acorn to check for actual `module.exports` syntax
if (src.match(/exports[\.( ?=)]/)) { return true };

if (
src.match(/require\(/)
&& !src.match(/createRequire\(/)
) return true;
Comment on lines +28 to +33
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be using /regex/.test here, much faster than 'string'.match as it doesn't need to create an array.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh, good call. I'll send an update this evening

}
8 changes: 8 additions & 0 deletions mixed-format/test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import assert from 'node:assert';

import { foo } from './fixture/esm.js';
import { qux } from './fixture/cjs.js';


assert.strictEqual(foo, 'bar');
assert.strictEqual(qux, 'zed');