Skip to content

Commit be1166f

Browse files
cjihrigtargos
authored andcommitted
esm: refactor createDynamicModule()
This commit refactors createDynamicModule() for readability: - The map() callback functions are named and moved to a higher scope. - The two export map() loops are combined. - JSON.stringify() is only called once per import. PR-URL: #27809 Reviewed-By: Gus Caplan <[email protected]> Reviewed-By: Daniel Bevenius <[email protected]> Reviewed-By: Guy Bedford <[email protected]> Reviewed-By: Jeremiah Senkpiel <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Yongsheng Zhang <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent a9f9557 commit be1166f

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

lib/internal/modules/esm/create_dynamic_module.js

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,27 @@ const { ArrayPrototype, JSON, Object } = primordials;
44

55
const debug = require('internal/util/debuglog').debuglog('esm');
66

7-
const createDynamicModule = (imports, exports, url = '', evaluate) => {
8-
debug('creating ESM facade for %s with exports: %j', url, exports);
9-
const names = ArrayPrototype.map(exports, (name) => `${name}`);
10-
11-
const source = `
12-
${ArrayPrototype.join(ArrayPrototype.map(imports, (impt, index) =>
13-
`import * as $import_${index} from ${JSON.stringify(impt)};
14-
import.meta.imports[${JSON.stringify(impt)}] = $import_${index};`), '\n')
7+
function createImport(impt, index) {
8+
const imptPath = JSON.stringify(impt);
9+
return `import * as $import_${index} from ${imptPath};
10+
import.meta.imports[${imptPath}] = $import_${index};`;
1511
}
16-
${ArrayPrototype.join(ArrayPrototype.map(names, (name) =>
17-
`let $${name};
12+
13+
function createExport(expt) {
14+
const name = `${expt}`;
15+
return `let $${name};
1816
export { $${name} as ${name} };
1917
import.meta.exports.${name} = {
2018
get: () => $${name},
2119
set: (v) => $${name} = v,
22-
};`), '\n')
20+
};`;
2321
}
2422

23+
const createDynamicModule = (imports, exports, url = '', evaluate) => {
24+
debug('creating ESM facade for %s with exports: %j', url, exports);
25+
const source = `
26+
${ArrayPrototype.join(ArrayPrototype.map(imports, createImport), '\n')}
27+
${ArrayPrototype.join(ArrayPrototype.map(exports, createExport), '\n')}
2528
import.meta.done();
2629
`;
2730
const { ModuleWrap, callbackMap } = internalBinding('module_wrap');

0 commit comments

Comments
 (0)