You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求适配Tailwind CSS v3的项目类使用分析工具(Next.js13+VSCode)

适配Tailwind CSS v3的类使用情况分析工具方案

针对你基于Next.js 13 + Tailwind CSS v3的大型项目,以下是几个可用于分析类使用频率、定位极少使用类的工具方案:

1. 升级后的tailwindcss-analysis(支持v3)

你提到的tailwindcss-analysis工具已更新适配Tailwind CSS v3,无需寻找替代工具,直接升级使用即可:

  • 安装依赖:
    npm install -D tailwindcss-analysis@latest
    # 或使用yarn
    yarn add -D tailwindcss-analysis@latest
    
  • 在package.json中添加脚本:
    {
      "scripts": {
        "tailwind-analyze": "tailwindcss-analysis"
      }
    }
    
  • 运行分析:
    npm run tailwind-analyze
    
    工具会启动本地可视化面板,展示所有Tailwind类的使用次数、未使用类,还能按组件/文件维度查看类的分布,方便你定位极少使用的类。

2. VS Code Tailwind CSS IntelliSense 扩展的统计功能

你正在使用VS Code,官方的Tailwind CSS IntelliSense扩展内置了类使用统计功能:

  • 确保扩展已安装并启用
  • 打开命令面板(Ctrl+Shift+P / Cmd+Shift+P),输入Tailwind CSS: Show Class Usage
  • 面板会列出项目中所有Tailwind类的使用次数,你可以按使用次数排序,快速筛选出极少使用的类

3. 自定义统计脚本(灵活适配需求)

如果上述工具满足不了自定义需求,可结合Tailwind的API编写简单脚本扫描项目文件:

  • 安装glob用于遍历文件:
    npm install -D glob
    
  • 创建tailwind-class-analyzer.js脚本:
    const fs = require('fs');
    const glob = require('glob');
    const { parse } = require('tailwindcss/lib/util/parse');
    
    // 定义要扫描的文件路径(根据你的项目调整)
    const files = glob.sync('./app/**/*.{js,ts,jsx,tsx}');
    const classUsage = {};
    
    files.forEach(filePath => {
      const content = fs.readFileSync(filePath, 'utf8');
      // 使用Tailwind的parse工具提取类名
      const classes = parse(content).reduce((acc, node) => {
        if (node.type === 'class') acc.push(...node.value.split(' '));
        return acc;
      }, []);
    
      classes.forEach(cls => {
        classUsage[cls] = (classUsage[cls] || 0) + 1;
      });
    });
    
    // 按使用次数排序输出
    const sortedClasses = Object.entries(classUsage).sort((a, b) => a[1] - b[1]);
    console.log('类使用统计(按使用次数升序):');
    sortedClasses.forEach(([cls, count]) => {
      console.log(`${cls}: ${count}次`);
    });
    
  • 运行脚本:
    node tailwind-class-analyzer.js
    
    脚本会输出所有类的使用次数,你可以根据结果筛选出需要合并的类,将其提取到全局CSS中。

内容的提问来源于stack exchange,提问作者Benjamin Fourgeaud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:20:06