PxToRem.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // 将项目中所有px单位除以100后替换成rem
  2. const fs = require('fs');
  3. const path = require('path');
  4. // 设置目标目录路径
  5. const targetDirectory = '../src';
  6. // 递归读取目录下的所有文件
  7. function readDirectory(dir) {
  8. const files = fs.readdirSync(dir);
  9. files.forEach((file) => {
  10. const filePath = path.join(dir, file);
  11. const stats = fs.statSync(filePath);
  12. if (stats.isDirectory()) {
  13. readDirectory(filePath); // 递归处理子目录
  14. } else if (
  15. path.extname(filePath) === '.less' ||
  16. path.extname(filePath) === '.js'
  17. ) {
  18. convertCssFile(filePath); // 处理 CSS 文件
  19. }
  20. });
  21. }
  22. // 转换 CSS 文件中的 px 单位为 rem 单位
  23. function convertCssFile(filePath) {
  24. const cssContent = fs.readFileSync(filePath, 'utf8');
  25. // 使用正则表达式替换 px 单位
  26. const remContent = cssContent.replace(/(\d*\.?\d+)px/g, (match, pxValue) => {
  27. const remValue = parseFloat(pxValue) / 100;
  28. return remValue + 'rem';
  29. });
  30. // 写入转换后的内容
  31. fs.writeFileSync(filePath, remContent, 'utf8');
  32. console.log(`Converted ${filePath}`);
  33. }
  34. // 启动脚本
  35. readDirectory(targetDirectory);