// 将项目中所有px单位除以100后替换成rem const fs = require('fs'); const path = require('path'); // 设置目标目录路径 const targetDirectory = '../src'; // 递归读取目录下的所有文件 function readDirectory(dir) { const files = fs.readdirSync(dir); files.forEach((file) => { const filePath = path.join(dir, file); const stats = fs.statSync(filePath); if (stats.isDirectory()) { readDirectory(filePath); // 递归处理子目录 } else if ( path.extname(filePath) === '.less' || path.extname(filePath) === '.js' ) { convertCssFile(filePath); // 处理 CSS 文件 } }); } // 转换 CSS 文件中的 px 单位为 rem 单位 function convertCssFile(filePath) { const cssContent = fs.readFileSync(filePath, 'utf8'); // 使用正则表达式替换 px 单位 const remContent = cssContent.replace(/(\d*\.?\d+)px/g, (match, pxValue) => { const remValue = parseFloat(pxValue) / 100; return remValue + 'rem'; }); // 写入转换后的内容 fs.writeFileSync(filePath, remContent, 'utf8'); console.log(`Converted ${filePath}`); } // 启动脚本 readDirectory(targetDirectory);