@@ -7,6 +7,9 @@ import { DocumentContext } from 'vscode-css-languageservice';
77import { endsWith , startsWith } from '../utils/strings' ;
88import * as url from 'url' ;
99import { WorkspaceFolder } from 'vscode-languageserver' ;
10+ import URI from 'vscode-uri' ;
11+ import { join , dirname } from 'path' ;
12+ import { existsSync } from 'fs' ;
1013
1114function getModuleNameFromPath ( path : string ) {
1215 // If a scoped module (starts with @) then get up until second instance of '/', otherwise get until first isntance of '/'
@@ -16,19 +19,14 @@ function getModuleNameFromPath(path: string) {
1619 return path . substring ( 0 , path . indexOf ( '/' ) ) ;
1720}
1821
19- function resolvePathToModule ( _moduleName : string , _relativeTo : string ) {
20- // if we require.resolve('my-module') then it will follow the main property in the linked package.json
21- // but we want the root of the module so resolve to the package.json and then trim
22- let resolved ;
23- try {
24- // resolved = require
25- // .resolve(`${moduleName}/package.json`, { paths: [relativeTo] });
26- throw new Error ( ) ;
22+ function resolvePathToModule ( _moduleName : string , _relativeTo : string ) : string | undefined {
23+ // resolve the module relative to the document. We can't use `require` here as the code is webpacked.
24+ const documentFolder = dirname ( URI . parse ( _relativeTo ) . fsPath ) ;
25+ const packPath = join ( documentFolder , 'node_modules' , _moduleName , 'package.json' ) ;
26+ if ( existsSync ( packPath ) ) {
27+ return URI . file ( packPath ) . toString ( ) ;
2728 }
28- catch ( ex ) {
29- return null ;
30- }
31- return resolved . slice ( 0 , - 12 ) ; // remove trailing `package.json`
29+ return undefined ;
3230}
3331
3432export function getDocumentContext ( documentUri : string , workspaceFolders : WorkspaceFolder [ ] ) : DocumentContext {
@@ -59,7 +57,7 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
5957 // and [sass-loader's](https://github.com/webpack-contrib/sass-loader#imports)
6058 // convention, if an import path starts with ~ then use node module resolution
6159 // *unless* it starts with "~/" as this refers to the user's home directory.
62- if ( ref [ 0 ] === '~' && ref [ 1 ] !== '/' ) {
60+ if ( ref [ 0 ] === '~' && ref [ 1 ] !== '/' && startsWith ( base , 'file://' ) ) {
6361 const moduleName = getModuleNameFromPath ( ref . substring ( 1 ) ) ;
6462 const modulePath = resolvePathToModule ( moduleName , base ) ;
6563 if ( modulePath ) {
0 commit comments