写一段脚本,批量刷代码

156 阅读1分钟

需求

给前端工程中使用的所有组件增加一个参数,用于自动化测试,此值需唯一。

<Button 刷成<Button autoId={uuid} ...

解决思路

  1. 几乎每个文件少则一两个组件,多则八九个,手敲过于费时费力。所以选择通过写脚本的方式,减少重复工作。

  2. 使用正则的replace和match,用match取想要的东西,利用replace将需要添加的东西替换上去。 具体说,每个文件中有哪些组件需要替换,一定是通过import引入的,那么我们拿到import引入的组件名,就可以在代码文件中进行匹配了。

替换结果

image.png

代码

const fs = require('fs');
// node path模块
const path = require('path');
// 收集所有的文件路径
const arr = [];
let timer = null;

const fileDisplay = (url, cb) => {
  const filePath = path.resolve(url);
  // 根据文件路径读取文件,返回文件列表
  fs.readdir(filePath, (err, files) => {
    if (err) return console.error('Error:(spec)', err);
    files.forEach((filename) => {
      // 获取当前文件的绝对路径
      const filedir = path.join(filePath, filename);
      // fs.stat(path)执行后,会将stats类的实例返回给其回调函数。
      fs.stat(filedir, (eror, stats) => {
        if (eror) return console.error('Error:(spec)', err);
        // 是否是文件
        const isFile = stats.isFile();
        // 是否是文件夹
        const isDir = stats.isDirectory();
        if (isFile) {
        // 过滤出所有后缀是.js的文件
          if (/.js$/.test(filedir)) {
            const rawFilePath = filedir;
            // 读取源文件
            const rawFile = fs.readFileSync(rawFilePath, 'utf-8');
            // 匹配import的组件 import xxxx from "antd"
            let antds = rawFile.match(/(.*)antd/);
            if (antds) {
            // 如果该js文件中引入组件
              antds = antds?.[0]?.match(/{(.*?)}/)?.[1];
              let allComp = '/';
              tinpers.split(',').map(comp => {
                comp = comp.trim();
                allComp += ('<' + comp + ' |');
              });
              allComp = allComp.slice(0, -1);
              allComp += '/gi';
              allComp = new RegExp(allComp, 'g');
              // 拼接autoId, 值为文件路径+组件名称+序号,以此保证唯一
              let allFieldPath = rawFilePath.split('/');
              const srcPathIndex = allFieldPath.findIndex(item => item === 'ucf-apps');
              allFieldPath = allFieldPath.slice(srcPathIndex + 1, -1).join('|');
              let count = 0;
              // 将符合条件的字符串拼接autoId,再替换原字符串
              const newData = rawFile.replace(allComp, (comp) => {
                return `${comp}autoid='design|${allFieldPath}|${comp.slice(1)}${count++}' `;
              });

              fs.writeFileSync(rawFilePath, newData);
            }
          }
          if (timer) clearTimeout(timer);
          timer = setTimeout(() => cb && cb(arr), 200);
        }
        // 如果是文件夹
        if (isDir) fileDisplay(filedir, cb);
      });
    });
  });
};
// 配置需要加autoId的文件夹
fileDisplay('./destinationDir', (arr) => {
  // console.log(arr, '-=')
});

module.exports = fileDisplay;

欢迎各位指出问题,提供更好的思路。