// 循环依赖
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'));