Skip to content

Commit

Permalink
esm: refactor createDynamicModule()
Browse files Browse the repository at this point in the history
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 <me@gus.host>
Reviewed-By: Daniel Bevenius <daniel.bevenius@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Jeremiah Senkpiel <fishrock123@rocketmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Yongsheng Zhang <zyszys98@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
cjihrig authored and targos committed May 28, 2019
1 parent a9f9557 commit be1166f
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions lib/internal/modules/esm/create_dynamic_module.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,27 @@ const { ArrayPrototype, JSON, Object } = primordials;

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

const createDynamicModule = (imports, exports, url = '', evaluate) => {
debug('creating ESM facade for %s with exports: %j', url, exports);
const names = ArrayPrototype.map(exports, (name) => `${name}`);

const source = `
${ArrayPrototype.join(ArrayPrototype.map(imports, (impt, index) =>
`import * as $import_${index} from ${JSON.stringify(impt)};
import.meta.imports[${JSON.stringify(impt)}] = $import_${index};`), '\n')
function createImport(impt, index) {
const imptPath = JSON.stringify(impt);
return `import * as $import_${index} from ${imptPath};
import.meta.imports[${imptPath}] = $import_${index};`;
}
${ArrayPrototype.join(ArrayPrototype.map(names, (name) =>
`let $${name};

function createExport(expt) {
const name = `${expt}`;
return `let $${name};
export { $${name} as ${name} };
import.meta.exports.${name} = {
get: () => $${name},
set: (v) => $${name} = v,
};`), '\n')
};`;
}

const createDynamicModule = (imports, exports, url = '', evaluate) => {
debug('creating ESM facade for %s with exports: %j', url, exports);
const source = `
${ArrayPrototype.join(ArrayPrototype.map(imports, createImport), '\n')}
${ArrayPrototype.join(ArrayPrototype.map(exports, createExport), '\n')}
import.meta.done();
`;
const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
Expand Down

0 comments on commit be1166f

Please sign in to comment.