|
1 | | -import type { HasDependency } from './types.js'; |
| 1 | +import { existsSync } from 'node:fs'; |
| 2 | +import { basename, dirname, join } from '../util/path.js'; |
| 3 | +import type { HasDependency, SyncCompilerFn } from './types.js'; |
2 | 4 |
|
3 | 5 | const condition = (hasDependency: HasDependency) => |
4 | 6 | hasDependency('sass') || hasDependency('sass-embedded') || hasDependency('node-sass'); |
5 | 7 |
|
6 | 8 | const importMatcher = /@(?:use|import|forward)\s+['"](pkg:)?([^'"]+)['"]/g; |
7 | 9 |
|
8 | | -const toRelative = (specifier: string) => (specifier.startsWith('.') ? specifier : `./${specifier}`); |
9 | | - |
10 | | -const compiler = (text: string) => { |
11 | | - const imports = []; |
12 | | - let match: RegExpExecArray | null; |
13 | | - let index = 0; |
14 | | - |
15 | | - // biome-ignore lint/suspicious/noAssignInExpressions: standard regex loop pattern |
16 | | - while ((match = importMatcher.exec(text))) { |
17 | | - if (match[2] && !match[2].startsWith('sass:')) |
18 | | - imports.push(`import _$${index++} from '${match[1] ? match[2] : toRelative(match[2])}';`); |
19 | | - } |
20 | | - |
21 | | - return imports.join('\n'); |
| 10 | +// Resolve _partials here to not soil the main resolver |
| 11 | +const resolvePartial = (specifier: string, containingFile: string) => { |
| 12 | + const rel = specifier.startsWith('.') ? specifier : `./${specifier}`; |
| 13 | + const name = basename(rel); |
| 14 | + if (name.startsWith('_')) return rel; |
| 15 | + const dir = dirname(rel); |
| 16 | + const partial = name.endsWith('.scss') ? `_${name}` : `_${name}.scss`; |
| 17 | + if (existsSync(join(dirname(containingFile), dir, partial))) return `${dir}/_${name}`; |
| 18 | + return rel; |
22 | 19 | }; |
23 | 20 |
|
| 21 | +const compiler: SyncCompilerFn = (text, filePath) => |
| 22 | + [...text.matchAll(importMatcher)] |
| 23 | + .filter(match => match[2] && !match[2].startsWith('sass:')) |
| 24 | + .map((match, i) => `import _$${i} from '${match[1] ? match[2] : resolvePartial(match[2], filePath)}';`) |
| 25 | + .join('\n'); |
| 26 | + |
24 | 27 | export default { condition, compiler }; |
0 commit comments