【问题标题】:How to find all imported (in code) dependencies within a TypeScript project?如何在 TypeScript 项目中查找所有导入的(代码中)依赖项?
【发布时间】:2021-01-27 11:55:59
【问题描述】:

我正在尝试使用 webpack 将第 3 方库捆绑到供应商捆绑包中,但这样做是通过扫描树中的所有 TypeScript 文件并以这种方式识别包导入并以数组形式返回它们,而不是手动维护一个依赖数组。

我在 npm 上找到了一个可以做到这一点的包,https://www.npmjs.com/package/find-imports - 但不幸的是,它只适用于 .js 文件,而不适用于 TypeScript。

非常感谢任何帮助。

【问题讨论】:

    标签: typescript webpack


    【解决方案1】:

    不确定这是否是您要查找的内容,但您可能想查看 webpack 的 require.context 功能。它允许您指定一个目录和一个正则表达式来匹配所包含文件的名称。

    以下示例从'path/to/folder' 导入与/\.ts$/ 匹配的所有文件。第二个参数true表示递归查询指定文件夹(包括子文件夹)。

    const myImports = require.context('path/to/folder', true, /\.ts$/);
    myImports.keys().forEach(myImports);
    

    【讨论】:

      【解决方案2】:

      试试AST generator

      // get them all
      const imports = sourceFile.getImportDeclarations();
      // or get the first one that matches a condition
      const importWithDefaultImport = sourceFile.getImportDeclaration(i => i.getDefaultImport() != null);
      const someModuleImport = sourceFile.getImportDeclaration("module-specifier-text");
      

      示例取自此页面:https://dsherret.github.io/ts-simple-ast/details/imports

      编辑:ts-simple-ast 已重命名为 ts-morph,请自行进一步研究。

      【讨论】:

        猜你喜欢
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多