handle require.resolve failure

if require.resolve fails, defer to default behaviour -url.resolve(base, ref)
This commit is contained in:
Alasdair McLeay
2019-03-18 15:51:37 +00:00
parent b1708589e1
commit 2e9bd074bb

View File

@@ -19,9 +19,15 @@ function getModuleNameFromPath(path: string) {
function resolvePathToModule(moduleName: string, relativeTo: string) {
// if we require.resolve('my-module') then it will follow the main property in the linked package.json
// but we want the root of the module so resolve to the package.json and then trim
return require
.resolve(`${moduleName}/package.json`, { paths: [relativeTo] })
.slice(0, -12); // remove trailing `package.json`
let resolved;
try {
resolved = require
.resolve(`${moduleName}/package.json`, { paths: [relativeTo] });
}
catch (ex) {
return null;
}
return resolved.slice(0, -12); // remove trailing `package.json`
}
export function getDocumentContext(documentUri: string, workspaceFolders: WorkspaceFolder[]): DocumentContext {
@@ -55,8 +61,10 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
if (ref[0] === '~' && ref[1] !== '/') {
const moduleName = getModuleNameFromPath(ref.substring(1));
const modulePath = resolvePathToModule(moduleName, base);
const pathWithinModule = ref.substring(moduleName.length + 2);
return url.resolve(modulePath, pathWithinModule);
if (modulePath) {
const pathWithinModule = ref.substring(moduleName.length + 2);
return url.resolve(modulePath, pathWithinModule);
}
}
return url.resolve(base, ref);
},