@@ -7,6 +7,9 @@ import { DocumentContext } from 'vscode-css-languageservice';
7
7
import { endsWith , startsWith } from '../utils/strings' ;
8
8
import * as url from 'url' ;
9
9
import { WorkspaceFolder } from 'vscode-languageserver' ;
10
+ import URI from 'vscode-uri' ;
11
+ import { join , dirname } from 'path' ;
12
+ import { existsSync } from 'fs' ;
10
13
11
14
function getModuleNameFromPath ( path : string ) {
12
15
// 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) {
16
19
return path . substring ( 0 , path . indexOf ( '/' ) ) ;
17
20
}
18
21
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 ( ) ;
27
28
}
28
- catch ( ex ) {
29
- return null ;
30
- }
31
- return resolved . slice ( 0 , - 12 ) ; // remove trailing `package.json`
29
+ return undefined ;
32
30
}
33
31
34
32
export function getDocumentContext ( documentUri : string , workspaceFolders : WorkspaceFolder [ ] ) : DocumentContext {
@@ -59,7 +57,7 @@ export function getDocumentContext(documentUri: string, workspaceFolders: Worksp
59
57
// and [sass-loader's](https://github.com/webpack-contrib/sass-loader#imports)
60
58
// convention, if an import path starts with ~ then use node module resolution
61
59
// *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://' ) ) {
63
61
const moduleName = getModuleNameFromPath ( ref . substring ( 1 ) ) ;
64
62
const modulePath = resolvePathToModule ( moduleName , base ) ;
65
63
if ( modulePath ) {
0 commit comments