How hezhuoyi/babel-plugin-rn-remove-unused-code works
Project type and purpose
• This is an open-source Babel plugin (babel-plugin-rn-remove-unused-code) written in TypeScript.
• Its purpose is to integrate into a React Native build (via Babel) and eliminate unused imports, styles, and PropTypes from JSX/JavaScript source files.
File structure
• Top level:
• babel.config.js – example of how the plugin is applied
• tsconfig.json, package.json – build/packaging
• README.md – usage and options
• Source code under babel-project/:
• index.ts – main plugin entrypoint (defines visitor methods for AST traversal)
• util.ts – helper functions for detecting and removing nodes
• types.d.ts – plugin options type definitions
• Build artifacts:
• The TS in babel-project is compiled (via tsc) to a dist/ folder when published.
README for additional insights
• Describes plugin options (imports.styles.propTypes), customization hooks, and example input/output.
• Reveals integration point (specified in a user’s babel.config.js).
Components
a. Input code module (JSX/JS files from React Native project)
b. Babel core (parser + traverse + generator)
c. Our plugin module:
– index.ts (visitor functions for ImportDeclaration, StyleSheet.create, ClassProperty(propTypes))
– util.ts (helpers to decide what to remove)
– types.d.ts (options interface)
d. Configuration loader (reads user’s plugin options from babel.config.js)
e. Output code module (transformed code)
f. Build pipeline (TypeScript compiler → dist/ folder → NPM publish)
Relationships and interactions
• User’s source code → fed into Babel parser
• Configuration loader injects plugin options into Babel
• Babel traverse invokes plugin visitor methods (index.ts)
• Visitors call util.ts functions to mark or remove AST nodes
• Modified AST is passed to Babel generator → output code
• The TypeScript compiler transforms TS sources into a distributable JS package
Architectural patterns and principles
• Plugin pattern (Babel’s visitor API)
• AST transformation pipeline
• Separation of concerns: index.ts (core logic) vs util.ts (helpers) vs types.d.ts (contracts)
• Build-step isolation: TS→JS compile before publish