figma-to-rn-toolkit
v2.0.0
Published
π¨ A comprehensive toolkit for converting Figma designs to React Native components with MCP (Model Context Protocol) support
Maintainers
Readme
Figma to React Native Toolkit
π Languages / θ―θ¨ιζ©: English | δΈζ
π¨ A comprehensive toolkit for automatically converting Figma designs to React Native components
π Introduction
Figma to React Native Toolkit is a powerful open-source toolkit designed specifically for automatically converting Figma designs into high-quality React Native components. It supports the latest MCP (Model Context Protocol) real-time access, making design-to-code conversion more efficient and accurate.
β¨ Key Features
- π¨ Smart Design Parsing - Automatically analyze Figma design structure and styles
- π± React Native Code Generation - Generate ready-to-use TypeScript components
- π Real-time MCP Support - Real-time Figma access through Model Context Protocol
- π― Precise Style Conversion - Perfect conversion from Figma styles to React Native StyleSheet
- π TypeScript Support - Complete type definitions and code completion
- π οΈ CLI Tools - Powerful command-line interface with batch processing support
- π§ Extensible Architecture - Modular design, easy to customize and extend
- π Cross-platform Compatibility - Supports Windows, macOS, and Linux
π¦ Installation
NPM Installation
npm install -g figma-to-rn-toolkitYarn Installation
yarn global add figma-to-rn-toolkitDevelopment Dependency Installation
npm install --save-dev figma-to-rn-toolkitποΈ System Requirements
- Node.js: >=16.0.0
- NPM: >=8.0.0
- React Native: >=0.65.0 (peerDependency)
- TypeScript: >=4.0.0 (recommended)
π― Quick Start
1. Get Figma Access Token
Go to Figma Settings > Personal Access Tokens to create a new access token:
Required Permission Settings:
- β File content β Read
- β Current user β Read
- β File metadata β Read
2. Configure Environment Variables
Create a .env file in your project root directory:
# Copy the example file
cp .env.example .env
# Edit the .env file and add your Figma token
FIGMA_TOKEN=your_figma_personal_access_token_hereSecurity Note: Never commit your .env file to version control. The .env file is already included in .gitignore to prevent accidental commits of sensitive information.
3. Basic Usage
Command Line Method (Recommended)
# Generate single component (token from environment variable)
figma-to-rn generate \
--token="$FIGMA_TOKEN" \
--url="https://www.figma.com/design/YOUR_FILE_ID/Design?node-id=NODE_ID" \
--output="./components" \
--name="CustomButton"
# Or explicitly provide token
figma-to-rn generate \
--token="YOUR_FIGMA_TOKEN" \
--url="https://www.figma.com/design/YOUR_FILE_ID/Design?node-id=NODE_ID" \
--output="./components" \
--name="CustomButton"
# Preview component information
figma-to-rn preview \
--token="$FIGMA_TOKEN" \
--url="YOUR_FIGMA_URL"
# Batch generate components
figma-to-rn batch \
--token="$FIGMA_TOKEN" \
--file="./urls.txt" \
--output="./components"Programmatic Usage
import { FigmaToReactNative } from 'figma-to-rn-toolkit';
import * as dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const converter = new FigmaToReactNative(process.env.FIGMA_TOKEN || '', {
outputPath: './components',
includeTypes: true,
useStyleSheet: true
});
const component = await converter.generateComponentFromUrl(
'https://www.figma.com/design/FILE_ID/Design?node-id=NODE_ID',
{
componentName: 'MyComponent',
writeToFile: true
}
);Node.js Script Method
For quick testing or to avoid command-line argument issues in Windows environments, you can use the included direct execution script:
Option 1: Use included script directly
node direct-run.jsOption 2: Modify the script for your needs
Edit direct-run.js and update the configuration:
const config = {
token: "YOUR_FIGMA_TOKEN",
url: "https://www.figma.com/design/YOUR_FILE_ID/Design?node-id=YOUR_NODE_ID",
output: "components",
name: "YourComponentName"
};Option 3: Create your own script
// Create your-script.js
const { FigmaToReactNative } = require('figma-to-rn-toolkit');
async function generateComponent() {
try {
const converter = new FigmaToReactNative('YOUR_FIGMA_TOKEN', {
outputPath: './components'
});
const component = await converter.generateComponentFromUrl(
'https://www.figma.com/design/YOUR_FILE_ID/Design?node-id=YOUR_NODE_ID',
{
componentName: 'CustomButton',
writeToFile: true
}
);
console.log(`β
Component ${component.name} generated successfully!`);
} catch (error) {
console.error('β Generation failed:', error.message);
}
}
generateComponent();3. MCP Real-time Access (Advanced Feature)
# Check MCP server status
figma-mcp status
# Connect to Figma MCP
figma-mcp connect
# Generate component from current selection
figma-mcp generate-selection
# Interactive mode
figma-mcp interactiveπ Feature Details
Supported Figma Features
| Feature | Support Status | Description | |---------|---------------|-------------| | Basic Shapes | β Full Support | Rectangles, circles, lines, etc. | | Text Styles | β Full Support | Font, size, color, alignment | | Auto Layout | β Full Support | Convert to Flexbox layout | | Color Fills | β Full Support | Solid colors, gradients | | Stroke Styles | β Full Support | Border styles and colors | | Border Radius | β Full Support | Uniform and individual corner radius | | Shadow Effects | β Full Support | Drop Shadow and Inner Shadow | | Opacity | β Full Support | Element transparency | | Component Instances | π Partial Support | Basic instance conversion | | Boolean Operations | π Partial Support | Convert to image assets | | Complex Paths | π Partial Support | Convert to SVG components | | Animations | β Not Supported | Planned for future versions |
Generated Code Structure
The tool generates React Native components similar to the following structure:
import React from 'react';
import { View, Text, StyleSheet, ViewStyle } from 'react-native';
interface CustomButtonProps {
title?: string;
onPress?: () => void;
style?: ViewStyle;
}
const CustomButton: React.FC<CustomButtonProps> = ({ title, onPress, style }) => {
return (
<View style={[styles.container, style]}>
<Text style={styles.text}>
{title || "Button"}
</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
width: 120,
height: 44,
backgroundColor: 'rgb(0, 122, 255)',
borderRadius: 8,
justifyContent: 'center',
alignItems: 'center'
},
text: {
fontFamily: 'System',
fontSize: 16,
fontWeight: '600',
color: 'rgb(255, 255, 255)'
}
});
export default CustomButton;π οΈ CLI Command Reference
generate Command
Generate React Native components
figma-to-rn generate [options]Options:
-t, --token <token>- Figma access token (required)-u, --url <url>- Figma component URL (required)-o, --output <path>- Output directory (default: ./components)-n, --name <name>- Custom component name--no-typescript- Generate JavaScript code--no-stylesheet- Use inline styles--tests- Generate test files--no-format- Skip code formatting
preview Command
Preview component information without generating code
figma-to-rn preview --token="TOKEN" --url="URL"batch Command
Batch process multiple components
figma-to-rn batch --token="TOKEN" --file="urls.txt" --output="./components"validate Command
Validate token and URL format
figma-to-rn validate --token="TOKEN" --url="URL"π§ Configuration Options
GenerationOptions Interface
interface GenerationOptions {
outputPath: string; // Output path
componentName?: string; // Component name
includeTypes?: boolean; // Generate TypeScript types
useStyleSheet?: boolean; // Use StyleSheet
generateTests?: boolean; // Generate test files
formatCode?: boolean; // Code formatting
}π API Reference
Main Classes
FigmaToReactNative
Main converter class
class FigmaToReactNative {
constructor(token: string, options?: FigmaOptions);
async generateComponentFromUrl(
url: string,
options?: GenerationOptions
): Promise<ComponentSpec>;
async validateToken(): Promise<boolean>;
async getFileInfo(fileKey: string): Promise<FigmaFile>;
}FigmaMCPIntegration
MCP integration class
class FigmaMCPIntegration {
constructor(options: MCPOptions);
async connect(): Promise<void>;
async generateFromSelection(options: GenerationOptions): Promise<ComponentSpec>;
async getContext(): Promise<MCPContext>;
}π¨ Troubleshooting
Common Issues
1. Token Permission Error (403 Forbidden)
Cause: Incorrect permission settings
Solution:
- Ensure correct permissions are set (File content, Current user, File metadata)
- Regenerate a new token
- Confirm the file is visible to your account
2. Node Not Found (404 Not Found)
Cause: Incorrect node ID or no access permission
Solution:
- Right-click the component in Figma and select "Copy link"
- Confirm the file and node are visible to you
- Check if the URL format is correct
3. Windows Command Line Issues
Problem: 'm' is not recognized as an internal or external command error
Solution:
# Use quotes around URLs
figma-to-rn generate --token="token" --url="complete URL" --output="./components"
# Or use Node.js script
node direct-run.jsπ€ Contributing Guidelines
We welcome community contributions! Please follow these steps:
Development Environment Setup
# Clone repository
git clone https://github.com/figma-to-rn-toolkit/figma-to-rn-toolkit.git
cd figma-to-rn-toolkit
# Install dependencies
npm install
# Build project
npm run build
# Run tests
npm test
# Start development mode
npm run devContribution Process
- Fork the project - Click the Fork button in the top right corner of the repository
- Create a branch -
git checkout -b feature/your-feature-name - Commit changes -
git commit -m "Add: your feature description" - Push branch -
git push origin feature/your-feature-name - Create PR - Create a Pull Request on GitHub
Code Standards
- Write code in TypeScript
- Follow ESLint configuration
- Add appropriate unit tests
- Update relevant documentation
π¦ NPM Version Release Process
For Maintainers: Publishing New Versions
1. Pre-release Checklist
# Ensure all tests pass
npm test
# Lint and format code
npm run lint:fix
npm run format
# Build the project
npm run build
# Verify build output
ls dist/2. Version Update
# For patch version (1.2.0 β 1.2.1)
npm version patch
# For minor version (1.2.0 β 1.3.0)
npm version minor
# For major version (1.2.0 β 2.0.0)
npm version major
# For pre-release (1.2.0 β 1.2.1-beta.0)
npm version prerelease --preid=beta3. Update Documentation
- Update CHANGELOG.md with new version features
- Update README if needed
- Verify all examples work with new version
4. Publish to NPM
# Publish stable version
npm publish
# Publish pre-release version
npm publish --tag beta
# Publish with specific tag
npm publish --tag next5. Post-publish Tasks
# Push changes and tags to GitHub
git push origin main
git push origin --tags
# Create GitHub release
gh release create v1.2.1 --title "v1.2.1" --notes "Release notes here"6. Automated Scripts
The project includes automated version management:
# These run automatically with npm version
npm run version # Formats code and stages changes
npm run postversion # Pushes to git and creates tags7. NPM Package Management
# Check package status
npm whoami
npm info figma-to-rn-toolkit
# Manage package access
npm owner ls figma-to-rn-toolkit
npm owner add <username> figma-to-rn-toolkit
# Deprecate old versions
npm deprecate [email protected] "Please upgrade to latest version"π Version Compatibility
| Toolkit Version | React Native | Node.js | TypeScript | |----------------|-------------|---------|------------| | 1.2.x | >=0.65.0 | >=16.0.0 | >=4.0.0 | | 1.1.x | >=0.63.0 | >=14.0.0 | >=3.8.0 | | 1.0.x | >=0.60.0 | >=12.0.0 | >=3.5.0 |
π Security
Token Security Best Practices
- Environment Variable Storage
# .env file
FIGMA_TOKEN=your_token_here
# Usage
figma-to-rn generate --token="${FIGMA_TOKEN}" --url="..."- CI/CD Integration
# GitHub Actions example
- name: Generate Components
env:
FIGMA_TOKEN: ${{ secrets.FIGMA_TOKEN }}
run: figma-to-rn batch --token="$FIGMA_TOKEN" --file="urls.txt"- Minimal Permissions
- Only grant necessary read permissions
- Regularly update tokens
- Don't hardcode tokens in code
Cursor Figma Plugin Integration
This toolkit works with the Cursor Figma plugin to provide AI-powered Figma-to-React-Native conversion.
How It Works
The Cursor Figma plugin has an implement-design skill that reads Figma design data via MCP and generates code. This toolkit provides React Native-specific design system rules (.cursor/rules/figma-design-system.mdc) that teach the plugin how to generate proper RN code -- using StyleSheet.create(), correct flexbox mapping, cross-platform shadows, proper component structure, etc.
Quick Setup for Any RN Project
Step 1: Install the Cursor Figma plugin (one-time, in Cursor IDE)
In Cursor Chat, type:
/add-plugin figmaStep 2: Copy RN design rules to your project
npx figma-rn-setup /path/to/your-rn-projectThis copies:
.cursor/rules/figma-design-system.mdc(RN-specific rules for the Figma plugin).cursorignore(excludesnode_modules,Pods,buildetc. from indexing)
Step 3: Use in Cursor Chat
Open your RN project in Cursor, then in Chat:
implement design https://figma.com/design/ABC123/MyApp?node-id=1-2The Figma plugin will read the design via MCP and generate a React Native component following the rules in figma-design-system.mdc.
Three Ways to Use This Toolkit
| Approach | When to Use | Command |
|----------|-------------|---------|
| A. Cursor Figma Plugin (AI) | Complex designs, responsive layouts, design token extraction | implement design <figma-url> in Cursor Chat |
| B. CLI (Deterministic) | Batch processing, CI/CD, reproducible output | npx figma-to-rn generate -u <url> -o ./src/components |
| C. Programmatic API | Custom pipelines, build tool integration | import { FigmaToReactNative } from 'figma-to-rn-toolkit' |
Approach A leverages the Cursor AI agent to interpret design intent and produce idiomatic RN code. Approach B uses the Figma REST API directly for deterministic output. Approach C gives full programmatic control for custom build pipelines.
π Changelog
v1.5.0
- Added Cursor Figma plugin integration with RN design system rules
- Added
figma-rn-setupCLI for one-command project setup - Fixed
package.jsonmain/types pointing to wrong entry - Fixed
tsconfig.jsonmissingmcp-cli.tsin includes - Added
.cursorignorefor Codebase Indexing optimization
v1.2.0
- β¨ Added MCP (Model Context Protocol) real-time access support
- π§ Improved Windows command-line compatibility
- π Complete TypeScript type definitions
- π¨ Optimized code generation quality
- π Fixed known issues
v1.1.0
- π Improved component structure parsing
- π± Enhanced React Native style conversion
- π οΈ Added batch processing functionality
- π Improved documentation and examples
v1.0.0
- π First stable release
- β Basic Figma API integration
- π± React Native component generation
- π οΈ CLI tools
π Getting Help
Community Support
- GitHub Issues: Report bugs or request features
- Discussions: Community discussions and Q&A
- Wiki: Detailed documentation and tutorials
Commercial Support
For professional support, custom development, or enterprise training, please contact:
- π§ Email: [email protected]
- π Website: https://figma-to-rn-toolkit.com
π License
This project is licensed under the MIT License.
MIT License
Copyright (c) 2025 Figma to RN Toolkit Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.π Acknowledgments
Thanks to the following projects and contributors:
- Figma API - Providing powerful design data access
- React Native - Cross-platform mobile application framework
- TypeScript - JavaScript type system
- All community members who contributed code, documentation, and feedback
π Changelog
[1.2.0] - 2025-01-04
Added
- β¨ Added MCP (Model Context Protocol) real-time access support
- π οΈ New
figma-mcpcommand-line tool - π‘ Implemented SSE (Server-Sent Events) event listening
- π Deep integration with Claude Code
- π Complete TypeScript type definitions and declaration files
- π§ͺ Added Jest testing framework configuration
- π Added ESLint and Prettier code standards
Improved
- π§ Optimized Windows command-line compatibility, resolved URL parsing issues
- π Fully respect user-specified output paths
- π·οΈ Fixed custom component name loss issue, added smart recovery mechanism
- π¨ Optimized code generation quality and readability
- π Enhanced README.md documentation with detailed usage guides
Fixed
- π Fixed command-line argument parsing errors on Windows systems
- π¨ Fixed issue where output path wasn't generated according to user specification
- π Fixed issue where component names were overwritten by original Figma names
- π Improved error handling and user-friendly error messages
Technical Improvements
- ποΈ Refactored NPM package structure with better modular design
- π¦ Optimized dependency management, reduced package size
- π Enhanced security, improved token handling mechanism
- π Improved build performance and development experience
[1.1.0] - 2025-01-02
Added
- π Added recursive text detection functionality
- π οΈ New batch processing capability
- π Added component preview functionality
Improved
- π¨ Improved component structure parsing algorithm
- π± Enhanced React Native style conversion accuracy
- π Enhanced documentation and usage examples
Fixed
- π Fixed missing Text component import issue
- π¨ Fixed nested component processing errors
- π Improved API error handling
[1.0.0] - 2025-01-01
Initial Release
- π Complete Figma to React Native conversion functionality
- β Basic Figma API integration
- π± React Native component code generation
- π οΈ CLI tool support
- π TypeScript support
- π¨ Style converter
- π Basic documentation
Version Notes
This project follows Semantic Versioning specifications:
- Major version: When you make incompatible API changes
- Minor version: When you add functionality in a backwards compatible manner
- Patch version: When you make backwards compatible bug fixes
π¨ Perfect Integration of Design and Code π
β Give us a Star | π Report Issues | π‘ Feature Requests
Made with β€οΈ by the Figma to RN Toolkit Team
