roid
roid copied to clipboard
循环引用和重复引用
我根据仓库中的源码和注释把代码重写了一遍,在编码和测试的过程中发现了2个问题:
1 循环引用
如果出现A <-> B两个文件互相引用了对方,目前版本的打包器会进入死循环,请问这个情况一般应该如何处理呢?
2 重复引用
如果出现在A和B中同时引用了C,那么C会以2个不同的id在graph对象中保留两份,如果被引用的次数变多可能还会持续生成多个副本,是不是可以提供一个判重的方法来去除打包后的重复代码?但是如果把判重写在当前的双层循环中可能会有性能问题,所以想请教一下作者这个部分应当如何去做?
@baxtergu 1.循环引用比较好做法就是断开他们的链接,使得他们变成 undefined 2.重复引用可以使用 hash 去重处理。
function parseGraph(entry) {
const entryAsset = parseDependecies(path.resolve(currentPath, entry))
const graph = [entryAsset]
for (const asset of graph) {
if (!asset.idMapping) asset.idMapping = {}
const dir = path.dirname(asset.filename)
asset.dependencies.forEach(dependencyPath => {
const absolutePath = path.resolve(dir, dependencyPath)
const denpendencyAsset = parseDependecies(absolutePath)
const id = denpendencyAsset.id
asset.idMapping[dependencyPath] = denpendencyAsset.id
graph.push(denpendencyAsset)
})
}
return graph
}
在parseGraph()这个函数中对默认的长度为1的graph使用for..of...循环,在循环体内又对graph进行了push操作,那么应该以什么样的一个条件去判断当前引用是循环引用然后去跳出内层循环呢?因为在生成graph的时候就卡住了