From 885d98efd3e9ee9a58889d13e8001b31af0bdbb6 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 30 Jun 2022 16:31:02 +0800 Subject: [PATCH] module: also enable subpath imports in REPL PR-URL: https://github.com/nodejs/node/pull/43450 Fixes: https://github.com/nodejs/node/issues/43410 Reviewed-By: Guy Bedford Reviewed-By: Antoine du Hamel Reviewed-By: James M Snell --- lib/internal/modules/cjs/loader.js | 27 ++++++++++++------------- test/es-module/test-esm-repl-imports.js | 19 +++++++++++++++++ 2 files changed, 32 insertions(+), 14 deletions(-) create mode 100644 test/es-module/test-esm-repl-imports.js diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 187394619bd..0cd2f5c2bae 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -909,20 +909,19 @@ Module._resolveFilename = function(request, parent, isMain, options) { paths = Module._resolveLookupPaths(request, parent); } - if (parent?.filename) { - if (request[0] === '#') { - const pkg = readPackageScope(parent.filename) || {}; - if (pkg.data?.imports != null) { - try { - return finalizeEsmResolution( - packageImportsResolve(request, pathToFileURL(parent.filename), - cjsConditions), request, parent.filename, - pkg.path); - } catch (e) { - if (e.code === 'ERR_MODULE_NOT_FOUND') - throw createEsmNotFoundErr(request); - throw e; - } + if (request[0] === '#' && (parent?.filename || parent?.id === '')) { + const parentPath = parent?.filename ?? process.cwd() + path.sep; + const pkg = readPackageScope(parentPath) || {}; + if (pkg.data?.imports != null) { + try { + return finalizeEsmResolution( + packageImportsResolve(request, pathToFileURL(parentPath), + cjsConditions), parentPath, request, + pkg.path); + } catch (e) { + if (e.code === 'ERR_MODULE_NOT_FOUND') + throw createEsmNotFoundErr(request); + throw e; } } } diff --git a/test/es-module/test-esm-repl-imports.js b/test/es-module/test-esm-repl-imports.js new file mode 100644 index 00000000000..d2b39e05fb0 --- /dev/null +++ b/test/es-module/test-esm-repl-imports.js @@ -0,0 +1,19 @@ +'use strict'; +const { mustCall } = require('../common'); +const assert = require('assert'); +const fixtures = require('../common/fixtures'); +const { spawn } = require('child_process'); + +const child = spawn(process.execPath, [ + '--interactive', +], { + cwd: fixtures.path('es-modules', 'pkgimports'), +}); + +child.stdin.end( + 'try{require("#test");await import("#test")}catch{process.exit(-1)}' +); + +child.on('exit', mustCall((code) => { + assert.strictEqual(code, 0); +}));