Skip to content

Commit

Permalink
fix: handle new node.js ESM quirks (#1723)
Browse files Browse the repository at this point in the history
  • Loading branch information
jchip authored Aug 26, 2020
1 parent a096596 commit d421006
Showing 1 changed file with 25 additions and 9 deletions.
34 changes: 25 additions & 9 deletions packages/electrode-node-resolver/lib/node-resolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,31 +29,47 @@ function isModuleRequest(request) {
}

function resolve(req, atPath) {
// can only resolve modules under node_modules
if (!isModuleRequest(req)) return undefined;
if (!isModuleRequest(req))
// can only resolve modules under node_modules
return undefined;

const splits = req.split("/");
const nameX = splits[0].startsWith("@") ? 2 : 1; // check for scoped module
const name = splits.slice(0, nameX).join("/");

const _xreq = requireAt(atPath);

//
// All modules must have package.json
//
const resolved = optionalRequire.resolve(
requireAt(atPath),
_xreq,
// some packages doesn't have index.js nor specify main so just require by
// its name will fail but we expect it to have a package.json file.
// ensure require request paths are POSIX
Path.posix.join(name, "package.json"),
false
Path.join(name, "package.json"),
{
default: false,
fail(err) {
// newer version of node.js with ESM support restrict importing
// files that're not specified in package.json
if (err.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
return optionalRequire.resolve(_xreq, name, false);
}
throw err;
}
}
);

if (!resolved) return undefined;

const ix = resolved.lastIndexOf(name);
const path = resolved.substr(0, ix + name.length);

splits.splice(0, nameX, ".");
const request = splits.join("/");

return {
path: Path.dirname(resolved),
request: splits.join("/")
};
return { path, request };
}

module.exports = {
Expand Down

0 comments on commit d421006

Please sign in to comment.