From be1166fd01b4f9451850d39e9acfaf0020204896 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 21 May 2019 23:07:26 -0400 Subject: [PATCH] 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: https://github.com/nodejs/node/pull/27809 Reviewed-By: Gus Caplan Reviewed-By: Daniel Bevenius Reviewed-By: Guy Bedford Reviewed-By: Jeremiah Senkpiel Reviewed-By: Luigi Pinca Reviewed-By: Yongsheng Zhang Reviewed-By: James M Snell --- .../modules/esm/create_dynamic_module.js | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/lib/internal/modules/esm/create_dynamic_module.js b/lib/internal/modules/esm/create_dynamic_module.js index 45f964d5ad8020..1201820003984f 100644 --- a/lib/internal/modules/esm/create_dynamic_module.js +++ b/lib/internal/modules/esm/create_dynamic_module.js @@ -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');