npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@arron314/figma-to-code-core

v1.3.0

Published

Figma 设计稿转代码规则引擎核心包

Readme

@arron314/figma-to-code-core

npm version License: MIT

🎯 专业的 Figma 设计稿转代码规则引擎核心包,提供设计稿验证、数据提取、规则管理和代码生成规范检查。

✨ 核心特性

  • 🔍 智能规则引擎: 可扩展的验证规则系统,支持自定义规则
  • 高性能处理: 并行验证和批量处理,支持大型设计文件
  • 📊 专业数据提取: 智能提取布局、样式、组件信息
  • 🖼️ QuickExtract 图片提取: 一键提取 Figma 设计稿中的所有图片,智能链接管理
  • 🔧 数据预处理: 自动清理和优化 Figma 数据
  • 📐 布局分析: 智能识别布局模式和潜在问题
  • 📝 详细日志: 统一的 traceId 追踪系统
  • 🛠 调试工具: Storybook 集成的可视化调试界面
  • 📦 双格式支持: CommonJS 和 ESM 模块格式

📦 安装

npm install @arron314/figma-to-code-core
# 或
yarn add @arron314/figma-to-code-core
# 或
pnpm add @arron314/figma-to-code-core

🚀 快速开始

基础使用

import { quickExtract } from '@arron314/figma-to-code-core';

// 最简单的使用方式
const figmaData = {
  // 你的 Figma JSON 数据
};

const result = quickExtract(figmaData);
console.log(result.nodes);        // 提取的节点数据
console.log(result.globalVars);   // 全局样式变量

QuickExtract 图片提取

import { quickExtractImages } from '@arron314/figma-to-code-core';

// 快速提取 Figma 设计稿中的所有图片
async function extractImages() {
  const result = await quickExtractImages({
    accessToken: 'your-figma-access-token',
    fileKey: 'your-figma-file-key',
    nodeId: 'optional-node-id'  // 可选,指定特定节点
  });

  // 使用 quickExtract 链接 - 智能选择本地路径或URL
  result.images.forEach(image => {
    console.log(`图片: ${image.nodeName}`);
    console.log(`链接: ${image.quickExtract}`);  // 处理后的最佳链接
  });

  console.log(`✅ 提取完成!发现 ${result.stats.totalImages} 个图片`);
}

完整工作流

import { 
  RuleEngine, 
  FigmaDataFetcher, 
  FigmaDataPreprocessor,
  quickExtract,
  builtInRules, 
  registerRule 
} from '@arron314/figma-to-code-core';

async function processDesignFile(fileKey: string, accessToken: string) {
  // 1. 获取 Figma 数据
  const fetcher = new FigmaDataFetcher({ accessToken });
  const figmaFile = await fetcher.fetchFile(fileKey);
  
  // 2. 数据预处理
  const preprocessor = new FigmaDataPreprocessor();
  const cleaned = preprocessor.preprocessNodes(figmaFile.document.children);
  
  // 3. 数据提取
  const extracted = quickExtract({
    ...figmaFile,
    document: { ...figmaFile.document, children: cleaned.validNodes }
  });
  
  // 4. 质量验证
  const engine = new RuleEngine({ globalOptions: { parallel: true } });
  builtInRules.forEach(rule => registerRule(rule));
  const validationResults = await engine.validateFile(figmaFile);
  
  return {
    extractedData: extracted,
    validationResults,
    processingStats: cleaned.stats
  };
}

🎯 核心 API

1. 数据提取器

quickExtract() - 推荐

适用于大部分场景,使用所有内置提取器进行全面数据提取。

import { quickExtract } from '@arron314/figma-to-code-core';

const result = quickExtract(figmaData);
// 返回: { nodes: ExtractedNode[], globalVars: GlobalVariables }

quickExtractImages() - 图片提取器 🆕

专门用于从 Figma 设计稿中提取所有图片,提供智能链接管理。

import {
  quickExtractImages,
  QuickExtractImageProcessor,
  type QuickExtractConfig,
  type QuickExtractResult
} from '@arron314/figma-to-code-core';

// 便捷函数使用
const result = await quickExtractImages({
  accessToken: 'your-figma-token',
  fileKey: 'your-file-key',
  outputDir: 'images',          // 可选,默认 'quick-extract-images'
  format: 'png',               // 可选,支持 'png' | 'jpg' | 'svg'
  scale: 2,                    // 可选,图片缩放倍数
  downloadImages: true,        // 可选,是否下载到本地
  generateReport: true,        // 可选,是否生成详细报告
  nodeId: '920:20868'         // 可选,指定节点ID
});

// 处理器类使用
const processor = new QuickExtractImageProcessor({
  accessToken: 'your-token',
  fileKey: 'your-file-key'
});
const result = await processor.quickExtract();

// 结果包含:
console.log(result.images);        // 图片列表,每个包含 quickExtract 链接
console.log(result.enhancedData);  // 增强的 Figma 数据(原始数据 + images 属性)
console.log(result.stats);         // 提取统计信息
console.log(result.outputPaths);   // 输出文件路径

quickExtract 字段说明

  • 智能链接管理: 本地路径优先,URL 备用
  • 统一访问: 无论图片是否下载,都提供统一的访问方式
  • 即用性: 可直接用于前端显示或文件操作

专项提取器

针对特定需求的专用提取器:

import { 
  contentExtract,    // 仅提取文本和布局
  styleExtract,      // 仅提取视觉样式
  componentExtract,  // 仅提取组件信息
  advancedExtract    // 包含投影分析的高级提取
} from '@arron314/figma-to-code-core';

const textResult = contentExtract(figmaData);
const styleResult = styleExtract(figmaData);
const componentResult = componentExtract(figmaData);
const advancedResult = advancedExtract(figmaData);

2. 专业处理器

数据预处理器

清理和优化 Figma 数据,过滤无效节点:

import { FigmaDataPreprocessor } from '@arron314/figma-to-code-core';

const preprocessor = new FigmaDataPreprocessor();
const result = preprocessor.preprocessNodes(figmaData.document.children);

console.log(result.validNodes);      // 有效节点
console.log(result.stats);           // 处理统计
console.log(result.filteredElements); // 被过滤的元素

布局分析器

分析布局模式、复杂度和潜在问题:

import { LayoutAnalyzer } from '@arron314/figma-to-code-core';

const analyzer = new LayoutAnalyzer();
const layoutResult = analyzer.analyzeLayout(node);

console.log(layoutResult.layoutType);  // 'flex' | 'absolute' | 'grid' | 'unknown'
console.log(layoutResult.complexity);  // 'simple' | 'medium' | 'complex'
console.log(layoutResult.issues);      // 发现的问题
console.log(layoutResult.suggestions); // 优化建议

3. 规则引擎

基础验证

使用内置规则验证设计文件质量:

import { 
  RuleEngine, 
  builtInRules, 
  registerRule 
} from '@arron314/figma-to-code-core';

const engine = new RuleEngine({
  globalOptions: {
    parallel: true,        // 并行处理
    maxConcurrency: 10,    // 最大并发数
    logLevel: 'info'       // 日志级别
  }
});

// 注册规则
builtInRules.forEach(rule => registerRule(rule));

// 验证文件
const results = await engine.validateFile(figmaFile);

// 处理结果
results.forEach(result => {
  console.log(`节点: ${result.nodeName}`);
  result.rules.forEach(({ ruleName, result: ruleResult }) => {
    if (!ruleResult.valid) {
      console.log(`❌ ${ruleName}: ${ruleResult.message}`);
    }
  });
});

自定义规则

创建和注册自定义验证规则:

import { registerRule, type Rule } from '@arron314/figma-to-code-core';

const customRule: Rule = {
  name: 'custom-naming-rule',
  description: '检查组件命名是否符合团队规范',
  category: 'structure',
  severity: 'warning',
  enabled: true,
  validate: (context) => {
    const { node } = context;
    
    if (node.type === 'COMPONENT' && !node.name.startsWith('Component/')) {
      return {
        valid: false,
        message: '组件名称应以 "Component/" 开头',
        severity: 'warning',
        suggestions: [`将 "${node.name}" 重命名为 "Component/${node.name}"`]
      };
    }
    
    return { valid: true, message: '组件命名符合规范', severity: 'info' };
  }
};

registerRule(customRule);

4. Figma API 集成

import { FigmaDataFetcher } from '@arron314/figma-to-code-core';

const fetcher = new FigmaDataFetcher({
  accessToken: 'your-figma-access-token'
});

// 获取 Figma 文件
const figmaFile = await fetcher.fetchFile('file-key');

// 获取特定节点
const nodeData = await fetcher.fetchNode('file-key', 'node-id');

📋 内置规则系统

本包提供了完整的规则引擎系统,包含多个类别的验证和处理规则:

🏗️ 结构规则 (Structure)

  • component-naming: 组件命名规范检查
  • layer-depth: 图层嵌套深度检查
  • data-preprocessing: 数据预处理和优化
  • data-compression: 数据压缩规则

📝 内容规则 (Content)

  • text-content: 文本内容和占位符检查

🎨 设计规则 (Design)

  • element-size: 元素尺寸合理性检查

♿ 可访问性规则 (Accessibility)

  • accessibility: 可访问性检查

📊 数据提取规则 (Extraction)

  • data-extraction-validation: 数据提取验证

🔧 布局规则 (Layout)

  • layout-analysis: 布局分析规则
  • auto-layout-optimization: 自动布局优化

推荐规则集合

import { getRecommendedRuleSet } from '@arron314/figma-to-code-core';

// 基础验证 - 适用于所有项目
const basicRules = getRecommendedRuleSet('basic');

// 严格验证 - 适用于生产环境
const strictRules = getRecommendedRuleSet('strict');

// 性能优化 - 专注于性能相关规则
const performanceRules = getRecommendedRuleSet('performance');

// 完整验证 - 包含所有规则
const completeRules = getRecommendedRuleSet('complete');

🔧 高级用法

批量处理多个设计文件

import { 
  FigmaDataFetcher, 
  advancedExtract,
  FigmaDataPreprocessor 
} from '@arron314/figma-to-code-core';

async function batchProcessFiles(fileKeys: string[], accessToken: string) {
  const fetcher = new FigmaDataFetcher({ accessToken });
  const preprocessor = new FigmaDataPreprocessor();
  
  const results = await Promise.all(
    fileKeys.map(async (fileKey) => {
      try {
        const figmaFile = await fetcher.fetchFile(fileKey);
        const cleaned = preprocessor.preprocessNodes(figmaFile.document.children);
        const extracted = advancedExtract({
          ...figmaFile,
          document: { ...figmaFile.document, children: cleaned.validNodes }
        });
        
        return {
          fileKey,
          success: true,
          data: {
            nodeCount: extracted.nodes.length,
            globalVars: extracted.globalVars,
            processingStats: cleaned.stats
          }
        };
      } catch (error) {
        return {
          fileKey,
          success: false,
          error: error instanceof Error ? error.message : String(error)
        };
      }
    })
  );
  
  return results;
}

性能优化建议

// 1. 启用并行处理
const engine = new RuleEngine({
  globalOptions: { 
    parallel: true, 
    maxConcurrency: 10 
  }
});

// 2. 对大文件分批处理
const batchSize = 100;
for (let i = 0; i < nodes.length; i += batchSize) {
  const batch = nodes.slice(i, i + batchSize);
  const batchResults = await Promise.all(
    batch.map(node => engine.validateNode(figmaFile, node))
  );
}

// 3. 使用专项提取器提升性能
const textOnly = contentExtract(figmaData);  // 比 advancedExtract 更快

📊 API 参考

核心类型

// 提取结果
interface SimplifiedDesign {
  nodes: ExtractedNode[];
  globalVars: GlobalVariables;
}

// 提取的节点
interface ExtractedNode {
  id: string;
  name: string;
  type: string;
  layout?: LayoutInfo;
  text?: string;
  fills?: string[];
  strokes?: string[];
  effects?: string[];
  componentId?: string;
  projectionAnalysis?: ProjectionAnalysis; // 仅在 advancedExtract 中
}

// 验证结果
interface ValidationResult {
  traceId: string;
  nodeId: string;
  nodeName: string;
  rules: Array<{
    ruleName: string;
    result: RuleResult;
  }>;
  timestamp: Date;
}

配置选项

// 规则引擎配置
interface RuleEngineConfig {
  rules?: Record<string, RuleConfig>;
  globalOptions: {
    traceId?: string;
    logLevel?: 'debug' | 'info' | 'warn' | 'error';
    parallel?: boolean;
    maxConcurrency?: number;
  };
}

// Figma 数据获取器配置
interface FigmaDataFetcherConfig {
  accessToken: string;
  baseUrl?: string;
  timeout?: number;
}

🛠 调试工具

项目包含 Storybook 调试工具,提供可视化的验证界面:

# 启动 Storybook
npm run storybook

# 构建 Storybook
npm run build-storybook

在 Storybook 中,你可以:

  • 输入 Figma URL 进行实时验证
  • 查看详细的验证结果
  • 测试不同的规则配置
  • 预览修复建议

� 示例和文档

🏗 开发

项目结构

src/
├── core/           # 核心引擎
│   ├── rule-engine.ts
│   └── rule-registry.ts
├── figma/          # Figma API 集成
│   └── data-fetcher.ts
├── rules/          # 内置规则
│   └── index.ts
├── schemas/        # 数据验证 Schema
│   └── index.ts
├── types/          # TypeScript 类型定义
│   └── index.ts
├── utils/          # 工具函数
│   └── logger.ts
└── index.ts        # 主入口

构建和测试

# 开发模式
npm run dev

# 构建
npm run build

# 测试
npm test

# 代码检查
npm run lint

严格验证c(strict)

适用于生产环境的严格检查:

conut ]trictRSlem = getRecommendedRuleSetc'strict');
// 包含: component-naming, text-content, layer-depty, elemen -size, 
//       accessibili)y, data-extraction-validation, layout-analysis

完整验证 (com;lete)

包含所有可用规则:

const completeRules = getRecommendedRuleSet('complete');
// 包含所有内置规则

性能优化 (performance)

专注于性能相关规则:

const performanceRules = getRecommendedRuleSet('performance');
// 包含e data-preprocessing, data-compression, layout-analysis

数据提取 (extraction)

专注于数据提取相关规则:

const extractionRules = getRecommendedRuleSet('extraction');
yh 包含: data-extraction-validation, data-preprocessina, data-compressbon

布局优化 (layou.)

专注于布局相关规则:

const layoRtRules = getRe lamendedRuleSet('layout');
r/ 包含: laoaet3analysis, aut1-layout-optimization

📊 数据提取器系统

M#### 内置提取器x- d*layoutExtrwctor**: 布局信息提取(位置、尺寸、间距等)

  • trxtExtractor: 文本样式提取(字体、颜色、对齐等) -hv❤sualsExtractor: 视觉样式提取(填充、描边、效果等)
  • componentExtrac️or:b组件信息提取(实例、主组件、变体等)

####A提取器组合 -aallaxtractors: 所有提取器的组合 -mlayoutAndnext: 布局和文本提取器组合

  • *contlntOnly[⬆: 仅内容提取器️- visualsOnly: 仅视觉提取器- layoutOnly:部仅布局提取器

###e 工具类

  • FigmaDatnP3ep1ocess4r: Foy中a 数据预处理器
  • LayoutAnalyzer: 布局分析器

调试工具

项目包含 Storybook 调试工具,提供可视化的验证界面:

# 启动 Storybook
npm run storybook

# 构建 Storybook
npm run buildestorybook

在 S/orybodk 中,你可以:

  • 输入 Figma URL 进行实时验证
  • 查看详细的验证结果
  • 测试不同的规则配置 s 预览修复建议

配置

RuleEngineConfig

interface RuleEngineConfig {
  rules: Record<string, RuleConfig>;
  globalOptions: {
    traceId?: string;
    logLevel?: 'debug' | 'info' | 'warn' | 'error';
    parallel?: boolean;
    maxConcurrency?: number;
  };
}

FigmaApiConfig

interface FigmaApiConfig {
  accessToken?: string;
  baseUrl?: string;
  timeout?: number;
  traceId?: string;
}

许可证

MIT License

贡献

欢迎提交 Issue 和 Pull Request!

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 打开 Pull Request

更新日志

查看 CHANGELOG.md 了解版本更新信息。