to-function-declaration
v1.2.0
Published
This lib will transform from arrow function to declaration with ES6 standard using typescript
Downloads
9
Maintainers
Readme
🛠️ to-function-declaration
🧹 Convert top-level arrow functions into function declarations — useful for enforcing consistent component declarations in React and ensuring readable, debuggable code.
✨ Features
- 🔁 Automatically converts top-level arrow functions or function expressions to function declarations
- ✅ Skips nested functions, inline handlers, and callbacks
- 🧠 Understands components: Only targets PascalCase functions when needed
- 💡 Supports JS, JSX, TS, TSX — fully compatible with React + TypeScript
- 👌 Supports extracting reusable type annotations.
- ⚙️ Optional flags for fine-grained control
📦 Installation
Use with npx (no install needed):
npx to-function-declaration ./src/pages/Home.tsxOr install globally:
npm install -g to-function-declaration🚀 Usage
to-function-declaration <file> [options]✅ Examples
Convert all top-level arrow functions in a file:
npx to-function-declaration src/utils/helpers.tsConvert all files in a folder (recursively):
npx to-function-declaration src/Convert only React components (PascalCase functions):
npx to-function-declaration src/components/MyComponent.tsx --component-onlySkip functions wrapped in HOCs like memo() or forwardRef():
npx to-function-declaration src/components/MyComponent.tsx --skip-hocExtract types:
npx to-function-declaration src/components/MyComponent.tsx --extract-typesBefore:
const MyComponent = ({ name }: { name: string }) => {
return <div>Hello, {name}</div>;
};After (--component-only --extract-types):
type MyComponentProps = {
name: string;
};
function MyComponent({ name }: MyComponentProps) {
return <div>Hello, {name}</div>;
}🧩 Options
Three options:
--component-only:
Only convert functions with PascalCase names (assumed to be React components). Useful if you only want to enforce consistency for components.
--skip-hoc:
Skip converting components that are passed into higher-order components like memo() or forwardRef(). These wrappers can obscure the function signature, so this option avoids potentially risky transforms.
--extract-types:
Extract inline props types to a separate Props type alias (TS only)
⚙️ How it works
This tool uses Babel and Recast to convert function definitions safely. Instead of parsing the function body in detail, it directly wraps the existing implementation into a function declaration — preserving:
async/awaitTypeScript annotations (return type, generics)
JSX and template literals
Comments and formatting
This makes it robust even in complex projects with modern syntax and avoids parser crashes from tricky RegExp patterns or nested template strings.
MIT @ Nhật Quang
