|
1 | 1 | const path = require('path') |
2 | | -const matchModuleImport = /^[^?]*~/ |
| 2 | + |
3 | 3 | /** |
4 | | - * Resolves the path to the file/module. |
| 4 | + * Resolve a Sass @import or @use rule. |
5 | 5 | * |
6 | | - * @param {String} to - the name of the file to resolve to |
7 | | - * @param {String} importPath - the local path |
8 | | - * @param {String} fileType - extension of the file to be resolved |
9 | | - * @returns {String} path - path to the file to import |
| 6 | + * @param {String} to - The path to the current file |
| 7 | + * @param {String} importPath - The path to resolve |
| 8 | + * @param {String} fileType - The filetype of the current file |
10 | 9 | */ |
11 | | -function resolve(to, importPath, fileType) { |
12 | | - importPath = |
13 | | - path.extname(importPath) === '' ? `${importPath}.${fileType}` : importPath |
| 10 | +function resolveSass(to, importPath, fileType) { |
| 11 | + // Mimic Sass-loader's `~` syntax for bare imports. |
| 12 | + const matchModuleImport = /^~/ |
14 | 13 |
|
15 | 14 | if (path.isAbsolute(importPath)) { |
16 | 15 | return importPath |
17 | 16 | } else if (matchModuleImport.test(importPath)) { |
18 | 17 | const dirname = path.dirname(importPath).replace(matchModuleImport, '') |
19 | 18 | const basename = path.basename(importPath) |
20 | 19 |
|
21 | | - try { |
22 | | - return require.resolve(path.join(dirname, basename)) |
23 | | - } catch (_) { |
24 | | - return require.resolve(path.join(dirname, `_${basename}`)) |
| 20 | + const filenames = [] |
| 21 | + |
| 22 | + if (!/\.(sc|sa|c)ss/.test(basename)) { |
| 23 | + const extensions = ['scss', 'sass', 'css'].filter(e => e !== fileType) |
| 24 | + extensions.unshift(fileType) |
| 25 | + extensions.forEach(ext => { |
| 26 | + filenames.push(`${basename}.${ext}`, `_${basename}.${ext}`) |
| 27 | + }) |
| 28 | + } else { |
| 29 | + filenames.push(basename, `_${basename}`) |
| 30 | + } |
| 31 | + |
| 32 | + for (const filename of filenames) { |
| 33 | + try { |
| 34 | + return require.resolve(path.join(dirname, filename)) |
| 35 | + } catch (_) {} |
25 | 36 | } |
26 | 37 | } |
| 38 | + |
27 | 39 | return path.join(path.dirname(to), importPath) |
28 | 40 | } |
29 | 41 |
|
@@ -61,5 +73,5 @@ module.exports = function applyModuleNameMapper( |
61 | 73 | ) |
62 | 74 | }, source) |
63 | 75 |
|
64 | | - return resolve(filePath, importPath, fileType) |
| 76 | + return resolveSass(filePath, importPath, fileType) |
65 | 77 | } |
0 commit comments