Created
May 4, 2023 08:45
-
-
Save BrantApps/1512d36168a209aafcd6afa1ace36e1f to your computer and use it in GitHub Desktop.
Remove assets that aren't used a particular flavour of a react-native app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const GET_FLAVORED_ASSET_FUNCTION_NAME = "getFlavoredAsset" | |
| module.exports = function ({types: t}) { | |
| const isGetFlavoredAssetCall = (path) => | |
| t.isIdentifier(path.node.callee, { | |
| name: GET_FLAVORED_ASSET_FUNCTION_NAME, | |
| }) && | |
| ((path.node.arguments.length === 1 && | |
| t.isObjectExpression(path.node.arguments[0])) || | |
| (path.node.arguments.length === 2 && | |
| t.isObjectExpression(path.node.arguments[0]) && | |
| t.isObjectExpression(path.node.arguments[1]))) | |
| const findObjectFlavorPropertyNode = (properties, flavor) => { | |
| return properties.find(({key: {name}}) => name === flavor)?.value | |
| } | |
| const findObjectPlatformsPropertyNode = (properties, targetPlatform) => { | |
| return ( | |
| !!properties && | |
| properties.find(({key: {name}}) => name === targetPlatform)?.value | |
| ) | |
| } | |
| const listTargetPlatforms = (properties) => { | |
| return properties.elements.map((it) => it.value) | |
| } | |
| return { | |
| visitor: { | |
| CallExpression(path, {filename, opts: {flavor, targetPlatform}}) { | |
| if (isGetFlavoredAssetCall(path)) { | |
| const flavorPropNode = findObjectFlavorPropertyNode( | |
| path.node.arguments[0].properties, | |
| flavor, | |
| ) | |
| if (!flavorPropNode) { | |
| throw new Error( | |
| `Unable to find a "${flavor}" prop in ${filename}:${path.node.loc.start.line}:${path.node.loc.start.column}-${path.node.loc.end.line}:${path.node.loc.end.column}. Check that your APP_VARIANT env var is set to a valid app variant and that all type errors have been resolved`, | |
| ) | |
| } | |
| const platformsPropNode = findObjectPlatformsPropertyNode( | |
| path.node.arguments[1] != null | |
| ? path.node.arguments[1].properties | |
| : null, | |
| "platforms", | |
| ) | |
| if (platformsPropNode && t.isArrayExpression(platformsPropNode)) { | |
| if ( | |
| listTargetPlatforms(platformsPropNode).includes(targetPlatform) | |
| ) { | |
| path.replaceWith(flavorPropNode) | |
| } else { | |
| path.remove() | |
| } | |
| } else { | |
| path.replaceWith(flavorPropNode) | |
| } | |
| } | |
| }, | |
| }, | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment