Skip to content

Commit

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

Node module resolution for CSS import
  • Loading branch information
aeschli authored Jun 4, 2019
2 parents 78378de + 2e9bd07 commit df9b668
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,28 @@ import { endsWith, startsWith } from '../utils/strings';
import * as url from 'url';
import { WorkspaceFolder } from 'vscode-languageserver';

function getModuleNameFromPath(path: string) {
// If a scoped module (starts with @) then get up until second instance of '/', otherwise get until first isntance of '/'
if (path[0] === '@') {
return path.substring(0, path.indexOf('/', path.indexOf('/') + 1));
}
return path.substring(0, path.indexOf('/'));
}

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
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 {
function getRootFolder(): string | undefined {
for (let folder of workspaceFolders) {
Expand All @@ -32,6 +54,18 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
}
}
}
// Following [css-loader](https://github.com/webpack-contrib/css-loader#url)
// and [sass-loader's](https://github.com/webpack-contrib/sass-loader#imports)
// convention, if an import path starts with ~ then use node module resolution
// *unless* it starts with "~/" as this refers to the user's home directory.
if (ref[0] === '~' && ref[1] !== '/') {
const moduleName = getModuleNameFromPath(ref.substring(1));
const modulePath = resolvePathToModule(moduleName, base);
if (modulePath) {
const pathWithinModule = ref.substring(moduleName.length + 2);
return url.resolve(modulePath, pathWithinModule);
}
}
return url.resolve(base, ref);
},
};
Expand Down

0 comments on commit df9b668

Please sign in to comment.