File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ exports . qux = require ( './cjs2.js' ) ;
Original file line number Diff line number Diff line change 1+ module . exports = 'zed' ;
Original file line number Diff line number Diff line change 1+ export const foo = 'bar' ;
Original file line number Diff line number Diff line change 1+ {
2+ "type" : " commonjs"
3+ }
Original file line number Diff line number Diff line change 1+ export async function load ( url , context , nextLoad ) {
2+ if ( ! url . endsWith ( '.js' ) ) return nextLoad ( url ) ;
3+
4+ const nextResult = await nextLoad ( url , { ...context , format : 'module' } )
5+ . then ( ( result ) => {
6+ if ( containsCJS ( result . source ) ) { throw new Error ( 'CommonJS' ) ; }
7+
8+ return result ;
9+ } )
10+ . catch ( async ( err ) => {
11+ if (
12+ ( err ?. message . includes ( 'require' ) && err . includes ( 'import' ) )
13+ || err ?. message . includes ( 'CommonJS' )
14+ ) {
15+ return { format : 'commonjs' } ;
16+ }
17+
18+ throw err ;
19+ } ) ;
20+
21+ return nextResult ;
22+ }
23+
24+ function containsCJS ( source ) {
25+ const src = '' + source ;
26+
27+ // A realistic version of this loader would use a parser like Acorn to check for actual `module.exports` syntax
28+ if ( src . match ( / e x p o r t s [ \. ( ? = ) ] / ) ) { return true } ;
29+
30+ if (
31+ src . match ( / r e q u i r e \( / )
32+ && ! src . match ( / c r e a t e R e q u i r e \( / )
33+ ) return true ;
34+ }
Original file line number Diff line number Diff line change 1+ import assert from 'node:assert' ;
2+
3+ import { foo } from './fixture/esm.js' ;
4+ import { qux } from './fixture/cjs.js' ;
5+
6+
7+ assert . strictEqual ( foo , 'bar' ) ;
8+ assert . strictEqual ( qux , 'zed' ) ;
You can’t perform that action at this time.
0 commit comments