Skip to content

Commit

Permalink
Merge pull request #81555 from penx/feature/node-module-resolution-fo…
Browse files Browse the repository at this point in the history
…r-css-import-parent-folders

CSS - Search in parent folders for node module resolution
  • Loading branch information
aeschli authored May 14, 2020
2 parents 869929e + 0fffab3 commit 815d94e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
10 changes: 10 additions & 0 deletions extensions/css-language-features/server/src/test/links.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,14 @@ suite('Links', () => {
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
);
});

test('node module subfolder resolving', function () {

let testUri = getTestResource('subdir/about.css');
let folders = [{ name: 'x', uri: getTestResource('') }];

assertLinks('html { background-image: url("~foo/hello.html|")',
[{ offset: 29, value: '"~foo/hello.html"', target: getTestResource('node_modules/foo/hello.html') }], testUri, folders
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@ function getModuleNameFromPath(path: string) {
return path.substring(0, path.indexOf('/'));
}

function resolvePathToModule(_moduleName: string, _relativeTo: string): string | undefined {
function resolvePathToModule(_moduleName: string, _relativeToFolder: string, _rootFolder: string | undefined): string | undefined {
// resolve the module relative to the document. We can't use `require` here as the code is webpacked.
const documentFolder = dirname(URI.parse(_relativeTo).fsPath);
const packPath = join(documentFolder, 'node_modules', _moduleName, 'package.json');

const packPath = join(_relativeToFolder, 'node_modules', _moduleName, 'package.json');
if (existsSync(packPath)) {
return URI.file(packPath).toString();
} else if (_rootFolder && _relativeToFolder.startsWith(_rootFolder) && (_relativeToFolder.length !== _rootFolder.length)) {
return resolvePathToModule(_moduleName, dirname(_relativeToFolder), _rootFolder);
}
return undefined;
}
Expand Down Expand Up @@ -61,7 +63,13 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
ref = ref.substring(1);
if (startsWith(base, 'file://')) {
const moduleName = getModuleNameFromPath(ref);
const modulePath = resolvePathToModule(moduleName, base);
const rootFolderUri = getRootFolder();
let rootFolder;
if (rootFolderUri) {
rootFolder = URI.parse(rootFolderUri).fsPath;
}
const documentFolder = dirname(URI.parse(base).fsPath);
const modulePath = resolvePathToModule(moduleName, documentFolder, rootFolder);
if (modulePath) {
const pathWithinModule = ref.substring(moduleName.length + 1);
return url.resolve(modulePath, pathWithinModule);
Expand Down

0 comments on commit 815d94e

Please sign in to comment.