Skip to content

Commit 934fc04

Browse files
committed
fix: 🐛 sass tilde importer
1 parent 550169c commit 934fc04

File tree

3 files changed

+41
-4
lines changed

3 files changed

+41
-4
lines changed

Diff for: .eslintrc

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"rules": {
88
"@typescript-eslint/no-explicit-any": "off",
99
"@typescript-eslint/ban-types": "off",
10-
"no-console": "off"
10+
"no-console": "off",
11+
"line-comment-position": "off"
1112
}
1213
}

Diff for: src/transformers/scss.ts

+34-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import { dirname, join } from 'path';
2+
import { existsSync } from 'fs';
3+
14
import type { Importer, Result } from 'sass';
25

36
import type { Transformer, Processed, Options } from '../types';
@@ -21,10 +24,38 @@ function getResultForResolve(result: Result): ResolveResult {
2124

2225
const tildeImporter: Importer = (url, _prev) => {
2326
if (url.startsWith('~')) {
24-
return { file: url.slice(1) };
27+
const cwd = process.cwd();
28+
29+
// not sure why this ends up here, but let's remove it
30+
_prev = _prev.replace('http://localhost', '');
31+
32+
// possible dirs where a node_modules may live in, includes cwd
33+
const possibleDirs = dirname(_prev).slice(cwd.length).split('/');
34+
35+
const existingNodeModules = possibleDirs
36+
// innermost dirs first
37+
.reverse()
38+
// return the first existing one
39+
.find((_, i, arr) => {
40+
const absPath = join(cwd, ...arr.slice(0, i + 1), 'node_modules');
41+
42+
return existsSync(absPath);
43+
});
44+
45+
// istanbul ignore if
46+
if (existingNodeModules == null) return null;
47+
48+
const resolvedUrl = join(
49+
cwd,
50+
existingNodeModules,
51+
'node_modules',
52+
url.slice(1),
53+
);
54+
55+
return { file: resolvedUrl };
2556
}
2657

27-
return { file: url };
58+
return null;
2859
};
2960

3061
const transformer: Transformer<Options.Sass> = async ({
@@ -49,6 +80,7 @@ const transformer: Transformer<Options.Sass> = async ({
4980

5081
const sassOptions = {
5182
...restOptions,
83+
file: filename,
5284
data: content,
5385
};
5486

Diff for: test/transformers/scss.test.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,10 @@ describe('transformer - scss', () => {
115115

116116
const preprocessed = await preprocess(template, opts);
117117

118-
expect(preprocessed.toString()).toContain('div{color:red}');
118+
expect(preprocessed.toString()).toMatchInlineSnapshot(`
119+
"<style lang=\\"scss\\">div {
120+
color: pink;
121+
}</style>"
122+
`);
119123
});
120124
});

0 commit comments

Comments
 (0)