Extracts the namespace of an `@use` rule from its parameters.
(params: string)
| 61 | |
| 62 | /** Extracts the namespace of an `@use` rule from its parameters. */ |
| 63 | function extractNamespaceFromUseStatement(params: string): string | null { |
| 64 | const openQuoteIndex = Math.max(params.indexOf(`"`), params.indexOf(`'`)); |
| 65 | const closeQuoteIndex = Math.max( |
| 66 | params.indexOf(`"`, openQuoteIndex + 1), |
| 67 | params.indexOf(`'`, openQuoteIndex + 1), |
| 68 | ); |
| 69 | |
| 70 | if (closeQuoteIndex > -1) { |
| 71 | const asExpression = 'as '; |
| 72 | const asIndex = params.indexOf(asExpression, closeQuoteIndex); |
| 73 | const withIndex = params.indexOf(' with', asIndex); |
| 74 | |
| 75 | // If we found an ` as ` expression, we consider the rest of the text as the namespace. |
| 76 | if (asIndex > -1) { |
| 77 | return withIndex == -1 |
| 78 | ? params.slice(asIndex + asExpression.length).trim() |
| 79 | : params.slice(asIndex + asExpression.length, withIndex).trim(); |
| 80 | } |
| 81 | |
| 82 | const importPath = params |
| 83 | .slice(openQuoteIndex + 1, closeQuoteIndex) |
| 84 | // Sass allows for leading underscores to be omitted and it technically supports .scss. |
| 85 | .replace(/^_|\.scss$/g, ''); |
| 86 | |
| 87 | // Built-in Sass imports look like `sass:map`. |
| 88 | if (importPath.startsWith('sass:')) { |
| 89 | return importPath.split('sass:')[1]; |
| 90 | } |
| 91 | |
| 92 | // Sass ignores `/index` and infers the namespace as the next segment in the path. |
| 93 | const fileName = basename(importPath); |
| 94 | return fileName === 'index' ? basename(join(fileName, '..')) : fileName; |
| 95 | } |
| 96 | |
| 97 | return null; |
| 98 | } |
| 99 | |
| 100 | export default createPlugin(ruleName, ruleFn); |