gulp 插件收集代碼中的註冊功能

需求:javascript

js 代碼中會用如下代碼註冊功能:java

when('car.name', { title: '車主姓名', dataIndex: 'buyerName', width: 150 }),
 when('car.phone', { title: '車主聯繫電話', dataIndex: 'buyerPhone', width: 150 }),
 when('car.chepai', { title: '車牌號', dataIndex: 'etPlateNumber', width: 150 }),
 when('car.mendian', { title: '門店', dataIndex: 'consignee', width: 150 }),

而後我須要在gulp build的時候,採集代碼中注入的這些key ,並生成一個對象。寫了gulp插件 bee.js 來作這件事情:json

/**
 * 採集代碼中的功能點。
 * 由於是靜態採集的方式,有不少問題,好比註釋中的代碼也會被採集。
 * 可是一種思路。
 */

const through = require('through2');
const chalk = require('chalk');
const path = require('path');
const pkg = require(path.join(process.cwd(), 'package.json'));
const fs = require('fs');
const _ = require('lodash');


function bee() {
  let latestFile;
  let latestMod;
  const petals = {};

  function bufferContents(file, encoding, callback) {
    if (file.isNull()) {
      throw 'NO Files,Please Check Files!';
    }

    if (file.isStream()) {
      this.emit('error', new Error('bee: Streaming not supported'));
      callback();
      return;
    }

    if (!latestMod || file.stat && file.stat.mtime > latestMod) {
      latestFile = file;
      latestMod = file.stat && file.stat.mtime;
    }

    if (file.isBuffer()) {
      const myRe = /when\('([\w|\.]+)/gm;
        // 拿到單個文件buffer
      const content = file.contents.toString('utf-8');
      const flowers = content.match(myRe);
      if (flowers) {
        const ps = flowers.map(petal => petal.replace("when('", ''));
        ps.forEach((p) => {
          if (!petals[p]) {
            petals[p] = 1;
          } else {
            petals[p] += 1;
          }
        });
      }
    }

    callback();
  }

  function endStream(cb) {
    if (!latestFile) {
      cb();
      return;
    }

    chalk.blue('採集到如下功能點:');
    console.log('採集到如下功能點:');
    console.log(Object.keys(petals));
    const features = {};
    Object.keys(petals).forEach((_path) => {
      _.set(features, _path, false);
    });
    pkg.features = features;
    fs.writeFile(path.join(process.cwd(), 'package.json'), JSON.stringify(pkg, null, 4), (err) => {
      if (err) return console.error(err);
      console.log('更新package.json 成功!');
    });
  }

  return through.obj(bufferContents, endStream);
}

module.exports = bee;

bee 插件收集完成後,會輸出到package.json中,下面就是運行後的結果:gulp

"features": {
        "baseInfo": {
            "id": false,
            "name": false
        },
        "car": {
            "name": false,
            "phone": false,
            "chepai": false,
            "mendian": false
        },
        "car4": false
    }
}
相關文章
相關標籤/搜索