| 9 | const globalStylesRegex = /(?<!\.module)\.(css|scss|sass)$/i |
| 10 | |
| 11 | export default function transformer( |
| 12 | file: FileInfo, |
| 13 | _api: API, |
| 14 | options: Options |
| 15 | ) { |
| 16 | const j = createParserFromPath(file.path) |
| 17 | const root = j(file.source) |
| 18 | let hasModifications = false |
| 19 | |
| 20 | root |
| 21 | .find(j.ImportDeclaration) |
| 22 | .filter((path) => { |
| 23 | const { |
| 24 | node: { |
| 25 | source: { value }, |
| 26 | }, |
| 27 | } = path |
| 28 | |
| 29 | if (typeof value === 'string') { |
| 30 | if (globalStylesRegex.test(value)) { |
| 31 | let resolvedPath = value |
| 32 | |
| 33 | if (value.startsWith('.')) { |
| 34 | resolvedPath = nodePath.resolve(nodePath.dirname(file.path), value) |
| 35 | } |
| 36 | globalCssContext.cssImports.add(resolvedPath) |
| 37 | |
| 38 | const { start, end } = path.node as any |
| 39 | |
| 40 | if (!path.parentPath.node.comments) { |
| 41 | path.parentPath.node.comments = [] |
| 42 | } |
| 43 | |
| 44 | path.parentPath.node.comments = [ |
| 45 | j.commentLine(' ' + file.source.substring(start, end)), |
| 46 | ] |
| 47 | hasModifications = true |
| 48 | return true |
| 49 | } else if (value.endsWith('.svg')) { |
| 50 | const isComponentImport = path.node.specifiers.some((specifier) => { |
| 51 | return (specifier as any).imported?.name === 'ReactComponent' |
| 52 | }) |
| 53 | |
| 54 | if (isComponentImport) { |
| 55 | globalCssContext.reactSvgImports.add(file.path) |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | return false |
| 60 | }) |
| 61 | .remove() |
| 62 | |
| 63 | return hasModifications && globalCssContext.reactSvgImports.size === 0 |
| 64 | ? root.toSource(options) |
| 65 | : null |
| 66 | } |