美文网首页让前端飞Web前端之路
使用 dpdm 定位 JavaScript/TypeScript

使用 dpdm 定位 JavaScript/TypeScript

作者: 一路行歌 | 来源:发表于2019-07-23 17:31 被阅读2次

    在写大型项目的时候, 一不小心就会踩到直接循环依赖的坑里面, 所谓直接循环依赖, 是指在模块工厂函数中, 对其它依赖于自己的模块的成员有直接调用的情况. 比如:

    假设有两个模块 a.jsb.js, 其中 a.js 的内容如下:

    const b = require('./b')
    
    exports.hello_a = function hello_a() {
      return 'a'
    }
    
    exports.hello_from_b = function hello_from_b() {
      return b.hello_b()
    }
    

    b.js 的内容如下:

    const a = require('./a')
    
    // 下面这一行导致了直接循环依赖
    exports.hello_from_a = a.hello_a()
    
    exports.hello_b = function hello_b() {
      return 'b'
    }
    

    这时, 执行 a.js, 会报 TypeError: a.hello_a is not a function 的错误, 这是因为模块 a.js 的工厂函数还在执行, 并且 hello_a 函数的声明尚未被执行, 而 b.js 就直接调用了 a.hello_a, 所以这个变量当成不存在, 也就报错了, 如果这不是一个函数而是一个变量, 则不会报错, 只是获取到的值为 undefined, 这种情况会更难定位问题.

    虽然现在有一个项目叫 madge 可以用来定位循环依赖, 但是这个仓库在处理 TypeScript 的时候的输出简直就是个玄学问题, 会常常莫名其妙的忽略掉了不应该被忽略掉的文件, 这个问题后面我会举例说明.

    所以我花了一天的时间来造了一个轮子: dpdm, 专门用来检测 JavaScriptTypeScript 项目中的循环依赖, 其目前可以检测下面这四种情况:

    • CommonJSrequire(...) 函数调用
    • ESM 的静态 import ... from ... 语句
    • ESM 的动态 import(...) 函数调用
    • ESM 的静态 export ... from ... 语句

    能满足大多数情况的需要, 因为现在极少有人有用 AMDSystem 了.

    使用方式

    1. 安装: dpdm 可以在命令行或者 js 项目中使用, 如果想在命令行使用(推荐), 则建议全局安装, 否则安装到你的项目中即可

      # 全局安装
      npm i -g dpdm # 或者用 yarn: yarn global add dpdm
      
      # 项目目录中安装
      npm i dpdm # 或者用 yarn: yarn add dpdm
      
    2. 在命令行中使用: 直接使用命令 dpdm [可选参数] <入口文件> 即可, 输出示例:

      image.png
    1. 默认情况下会输出依赖树(tree), 循环依赖列表(circular), 以及警示信息(warning), 你可以使用参数关闭掉其中任意项, 比如 `dpdm --tree false --warning false ./src/index.ts` 来关闭依赖树和警示信息(仅展示循环依赖表).
    2. 可以使用 `--output <file>` 来输出结果到 json 文件中
    3. 默认情况下忽略了 `node_modules` 中的内容, 可以使用 `--exclude ''` 来取消忽略
    4. 使用 `--help` 查看完整的帮助文档:
    
        ```bash
        dpdm --help
        dpdm [<options>] entry...
    
        Options:
          --version            Show version number                                                                     [boolean]
          --context            the context directory to shorten path, default is process.cwd()                          [string]
          --extensions, --ext  comma separated extensions to resolve          [string] [default: ".ts,.tsx,.mjs,.js,.jsx,.json"]
          --include            included filenames regexp in string                            [string] [default: "\.m?[tj]sx?$"]
          --exclude            excluded filenames regexp in string                          [string] [default: "/node_modules/"]
          --output, -o         output json to file                                                                      [string]
          --tree               print tree to stdout                                                    [boolean] [default: true]
          --circular           print circular to stdout                                                [boolean] [default: true]
          --warning            print warning to stdout                                                 [boolean] [default: true]
          -h, --help           Show help                                                                               [boolean]
        ```
    
    1. 在代码中使用: dpdm 提供了若干 API, 具体可以查看包中提供的 .d.ts 提供的定义, 或者到 GitHub 查看文档:

      image.png
    比如:
    
    ```ts
    import {
      parseCircular,
      parseDependencyTree,
      parseWarnings,
      prettyCircular,
      prettyTree,
      prettyWarning,
    } from 'dpdm';
    
    parseDependencyTree(['./src/**/*'] /* 入口, glob 匹配, 可以是数组 */, {
      /* 参数列表, 下面这些是默认参数 */
      context: process.cwd(), // 前缀, 用来简写文件名
      extensions: ['', '.ts', '.tsx', '.mjs', '.js', '.jsx', '.json'], // 后缀
      include: /\.m?[tj]sx?$/, // 需要解析的文件
      exclude: /\/node_modules\//, // 需要忽略的文件
    }).then((tree) => {
      console.log('Tree:');
      console.log(prettyTree(tree, Object.keys(tree)));
      console.log('');
      console.log('Circular:');
      console.log(prettyCircular(parseCircular(tree)));
      console.log('');
      console.log('Warning:');
      console.log(prettyWarning(parseWarnings(tree)));
    });
    ```
    

    提问题

    项目在 GitHub 已开源, 地址是 https://github.com/acrazing/dpdm, 你可以到上面提 issue 或者提交 pr.

    顺便, 求赞~

    相关文章

      网友评论

        本文标题:使用 dpdm 定位 JavaScript/TypeScript

        本文链接:https://www.haomeiwen.com/subject/kpmalctx.html