-
Notifications
You must be signed in to change notification settings - Fork 300
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
extract node resolver to common module in lib
- Loading branch information
Showing
2 changed files
with
67 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
packages/electrode-archetype-react-app-dev/lib/node-resolver.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
"use strict"; | ||
|
||
/* eslint-disable prefer-template */ | ||
|
||
const Path = require("path"); | ||
const requireAt = require("require-at"); | ||
const optionalRequire = require("optional-require"); | ||
|
||
function isModuleRequest(request) { | ||
// | ||
// If request is not an absolute/relative path then it's requiring a | ||
// nodejs module. | ||
// | ||
if (Path.isAbsolute(request)) return false; | ||
|
||
if (request === "." || request === "..") { | ||
return false; | ||
} | ||
|
||
if (request.startsWith("../") || request.startsWith("./")) { | ||
return false; | ||
} | ||
|
||
if (Path.sep !== "/") { | ||
return !request.startsWith("." + Path.sep) || !request.startsWith(".." + Path.sep); | ||
} | ||
|
||
return true; | ||
} | ||
|
||
function resolve(req, atPath) { | ||
if (!isModuleRequest(req)) return undefined; | ||
|
||
const splits = req.split("/"); | ||
const nameX = splits[0].startsWith("@") ? 2 : 1; // check for scoped module | ||
const name = splits.slice(0, nameX).join("/"); | ||
|
||
// | ||
// All modules must have package.json | ||
// | ||
const resolved = optionalRequire.resolve( | ||
requireAt(atPath), | ||
// ensure require request paths are POSIX | ||
Path.posix.join(name, "package.json"), | ||
false | ||
); | ||
|
||
if (!resolved) return undefined; | ||
|
||
splits.splice(0, nameX, "."); | ||
|
||
return { | ||
path: Path.dirname(resolved), | ||
request: splits.join("/") | ||
}; | ||
} | ||
|
||
module.exports = { | ||
isModuleRequest, | ||
resolve | ||
}; |