判断通过es6导入的模块是否存在循环引用

// 循环依赖
const fs = require('fs');
const { basename, dirname, resolve } = require('path');
const dep_cache = {};
const reg = /(?<=from\s+['"])[\.\/\w]+(?=['"])/g;
function estimateRepeatDep (entry, prePath = '.') {
  let temp = null;
  // 是否为循环依赖
  let flag = false;
  const name = basename(entry);
  const dir = resolve(prePath, dirname(entry));
  const path = resolve(prePath, entry);
  const readFile = Buffer.from(fs.readFileSync(path)).toString();
  const cache = [];
  while ((temp = reg.exec(readFile)) !== null) {
    cache.push(...temp.map(filePath => resolve(dir, ~filePath.indexOf('.js') ? filePath : `${filePath}.js`)));
  }
    dep_cache[path] = {
      name,
      dir,
      path,
      cache
    };
    cache.forEach(c => {
      if (dep_cache[c] && dep_cache[c].cache.includes(resolve(path))) {
        flag = true;
      }
    });
    for (let i = 0, length = cache.length;i < length; ++i) {
      if (flag) {
        break;
      }
      flag = estimateRepeatDep(cache[i], dir)
    }
    return flag;
}
console.log(estimateRepeatDep('../d.js'));

posted @ 2020-10-06 15:18  代码男孩  阅读(322)  评论(0编辑  收藏  举报