从一个例子开始,测试项目project里面有三个文件

  • project/index.js
  1. import a from './a.js'
  2. import b from './b.js'
  3. console.log(a.value + b.value)
  • project/a.js
  1. const a = {
  2. value: 1,
  3. }
  4. export default a
  • project/b.js
  1. const b = {
  2. value: 2,
  3. }
  4. export default b

依赖关系是 index -> a,b

新建一个deps.ts文件,用来分析我们的project所有依赖,主要代码为以下四行

  1. // 设置根目录
  2. const projectRoot = resolve(__dirname, 'project')
  3. // 类型声明
  4. type DepRelation = { [key: string]: { deps: string[], code: string } }
  5. // 初始化一个空的 depRelation,用于收集依赖
  6. const depRelation: DepRelation = {}
  7. // 将入口文件的绝对路径传入函数
  8. collectCodeAndDeps(resolve(projectRoot, 'index.js'))
  9. console.log(depRelation)
  10. console.log('done')
  11. // node -r ts-node/register deps.ts 运行一下

得到一个对象,它包含了index.js文件的所有依赖

  1. {
  2. // 对象的key是index.js
  3. 'index.js': {
  4. // 依赖
  5. deps: ['a.js', 'b.js'],
  6. // index.js源代码
  7. code: 'import a from \'./a.js\'\nimport b from \'./b.js\'\nconsole.log(a.value + b.value)\n'
  8. }
  9. }

知道deps.ts的功能了,具体分析一下collectCodeAndDeps方法的思路

  1. function collectCodeAndDeps(filepath: string) {
  2. const key = getProjectPath(filepath) // 文件的项目路径,如 index.js
  3. // 获取文件内容,将内容放至 depRelation
  4. const code = readFileSync(filepath).toString()
  5. // 初始化 depRelation[key]
  6. depRelation[key] = { deps: [], code: code }
  7. // 将代码转为 AST,主要是为了看看文件有哪些import语句✅
  8. const ast = parse(code, { sourceType: 'module' })
  9. // 分析文件依赖,将内容放至 depRelation
  10. traverse(ast, {
  11. enter: path => {
  12. // 如果节点中有import类型声明
  13. if (path.node.type === 'ImportDeclaration') {
  14. // path.node.source.value 往往是一个相对路径,如 ./a.js,需要先把它转为一个绝对路径
  15. const depAbsolutePath = resolve(dirname(filepath), path.node.source.value)
  16. // 然后转为项目路径
  17. const depProjectPath = getProjectPath(depAbsolutePath)
  18. // 把依赖写进 depRelation[index.js]
  19. depRelation[key].deps.push(depProjectPath)
  20. }
  21. }
  22. })
  23. }
  24. // 获取文件相对于根目录的相对路径
  25. function getProjectPath(path: string) {
  26. return relative(projectRoot, path).replace(/\\/g, '/')
  27. }

最终的depRelation就收集了index.js的依赖,这样我们使用一个对象,就可以存储文件的依赖

升级 依赖的依赖

比如这样:

  1. index -> a -> dir/a2 -> dir/dir_in_dir/a3
  2. index -> b -> dir/b2 -> dir/dir_in_dir/b3

可以通过不断的调用collectCodeAndDeps方法来收集全部的依赖,其实就是一个递归
那么,刚刚的代码中,只需要变动一处即可实现这个方法

  1. traverse(ast, {
  2. enter: path => {
  3. if (path.node.type === 'ImportDeclaration') {
  4. ...
  5. // 收集依赖的依赖
  6. collectCodeAndDeps(depAbsolutePath) // 加上这行✅
  7. ...
  8. }
  9. }
  10. })

使用递归获取嵌套依赖,从而可以通过一个入口文件获得整个项目的依赖

但是,递归存在 call stack 溢出的风险,比如潜逃层数过多,超过20000?程序直接崩溃

比如:

  1. index -> a -> b
  2. index -> b -> a
  3. ...
  4. // a.value = b.value + 1
  5. // b.value = a.value + 1

调用栈溢出,那是因为a -> b -> a -> b -> a -> b -> … 把调用栈撑满了

怎么解决循环依赖导致调用栈溢出?

需要一些小技巧,比如,一旦发现这个 key 已经在 keys 里了,就 return

  1. function collectCodeAndDeps(filepath: string) {
  2. ...
  3. if (Object.keys(depRelation).includes(key)) {
  4. console.warn(`duplicated dependency: ${key}`)
  5. return
  6. }
  7. ...

这样分析过程就不是 a -> b -> a -> b -> … 而是 a -> b -> return

不过,以上循环依赖的例子,是有逻辑漏洞的,因为在实际运行中还是会报错(只是一个例子方便我们进行静态分析),除非给ab一个初始值

总结

  • 使用对象来存储文件依赖关系
  • 通过检测key来避免重复