|
| 1 | + |
| 2 | +/** |
| 3 | + * Checks if there are any remaining imports from `babel-plugin-solid-undestructure`. |
| 4 | + * If there are any remaining imports and any of them are used, an error is thrown. |
| 5 | + * Otherwise, if none are used, the remaining imports are removed. |
| 6 | + */ |
| 7 | +const handleRemainingPluginImports = programPath => { |
| 8 | + const pluginImportPaths = getPluginImportPaths(programPath) |
| 9 | + |
| 10 | + if (pluginImportPaths.length > 0) { |
| 11 | + const bindings = programPath.scope.bindings |
| 12 | + |
| 13 | + let someImportIsUsed = checkIfAnyImportsAreUsed(pluginImportPaths, bindings) |
| 14 | + |
| 15 | + if (someImportIsUsed) { |
| 16 | + throw new Error( |
| 17 | +`babel-plugin-undestructure error: An import from 'babel-plugin-undestructure' remained after applying the transformation. |
| 18 | +This is either a configuration problem or a bug in the plugin. |
| 19 | +If the plugin is configured correctly, please open an issue on GitHub.` |
| 20 | + ) |
| 21 | + } |
| 22 | + |
| 23 | + // Remove the import declarations. |
| 24 | + for (const importDeclarationPath of pluginImportPaths) |
| 25 | + importDeclarationPath.remove() |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +function checkIfAnyImportsAreUsed(pluginImportPaths, bindings) { |
| 30 | + let someImportIsUsed = false |
| 31 | + |
| 32 | + for (const importDeclarationPath of pluginImportPaths){ |
| 33 | + const importDeclaration = importDeclarationPath.node |
| 34 | + for (const specifier of importDeclaration.specifiers) |
| 35 | + if (bindings[specifier.local.name].references >= 1) |
| 36 | + someImportIsUsed = true |
| 37 | + } |
| 38 | + |
| 39 | + return someImportIsUsed |
| 40 | +} |
| 41 | + |
| 42 | +function getPluginImportPaths(programPath) { |
| 43 | + const bodyLength = programPath.node.body.length |
| 44 | + const pluginImportPaths = [] |
| 45 | + |
| 46 | + for (let i = 0; i < bodyLength; i++) { |
| 47 | + const node = programPath.node.body[i] |
| 48 | + |
| 49 | + if ( |
| 50 | + node.type === 'ImportDeclaration' |
| 51 | + && node.source.value === 'babel-plugin-solid-undestructure' |
| 52 | + ) |
| 53 | + pluginImportPaths.push(programPath.get(`body.${i}`)) |
| 54 | + } |
| 55 | + |
| 56 | + return pluginImportPaths |
| 57 | +} |
| 58 | + |
| 59 | +module.exports.handleRemainingPluginImports = handleRemainingPluginImports |
0 commit comments