从 TypeScript 文件收集参考依赖关系树

Jas*_*ban 4 caching ondemand typescript

问题:

关于在服务器端编译 TypeScript 代码,有没有办法获取单个 .ts 文件的所有引用路径的列表 - 或者更好的是整个编译(从单个 .ts 文件开始)?按顺序,最好。

如果可能的话,我更愿意使用现有的解析器,而不是使用新代码解析文件。

语境:

因为我认为它不完全存在,所以我想写:

  1. 一个服务器端 Web 用户控件,它采用 .ts 路径并生成指向的缓存清除脚本标记
  2. 一个 HttpHandler,它在第一次请求时编译所请求的 .ts 文件一次,然后将 CacheDependency 添加到所有引用依赖项路径。当文件更改时,生成脚本的 Web 用户控件会更新其后续请求的缓存清除后缀。

所以在发布模式下,<tsb:typescript root="app.ts" runat="server" />产生

<script type="text/javascript" src="app.ts?32490839"></script>
Run Code Online (Sandbox Code Playgroud)

其中交付的脚本是按需缓存的单文件脚本。

在调试模式下,未修改的标签会产生:

<script type="text/javascript" src="dependency1.ts?32490839"></script>
<script type="text/javascript" src="dependency2.ts?32490839"></script>
<script type="text/javascript" src="app.ts?32490839"></script>
Run Code Online (Sandbox Code Playgroud)

据我所知,TypeScript Visual Studio 插件和任何 Optimizer 捆绑程序都不支持这种操作模式。捆绑器的功能接近我的要求,但它们不会破坏缓存,也不会在没有烦人的显式捆绑文件的情况下进行单文件编译。

我不介意在编译脚本时的第一个请求时出现任何性能影响。除此之外,也许有一个非常重要的理由表明这种设置不应该或不能存在。如果这不能或显然不应该这样做,我也很感激这样的答案。

我在 StackOverflow 上看到过其他问题,这些问题在我的解释中都围绕着这个愿望,但没有像这个这样明确的问题,也没有相关的答案。

谢谢!

另外,在不同的进程中执行 tsc.exe 是我的 HttpHandler 在运行时编译的最佳方法还是有一种灵活、安全且简单的方法在进程内执行此操作?

Jas*_*ban 5

2021 年我们有--explainFiles

如果您想更仔细地检查代码库(例如区分仅类型导入和运行时导入),可以使用 Typescript API。可能性是无限的,但也许下面的这些部分可以帮助您找到一个好的方向(可能有错误):

import * as ts from "typescript";

interface FoundReference {
    typeOnly: boolean;
    relativePathReference: boolean;
    referencingPath: string;
    referencedSpecifier: string;
}

const specifierRelativeFile = /^\..*(?<!\.(less|svg|png|woff))$/;
const specifierNodeModule = /^[^\.]/;

const diveDeeper = (path: string, node: ts.Node, found: FoundReference[]) =>
    Promise.all(node.getChildren().map(n => findAllReferencesNode(path, n, found)));

const findAllReferencesNode = async (path: string, node: ts.Node, found: FoundReference[]) => {
    switch (node.kind) {
        case ts.SyntaxKind.ExportDeclaration:
            const exportDeclaration = node as ts.ExportDeclaration;

            if (exportDeclaration.moduleSpecifier) {
                const specifier = (exportDeclaration.moduleSpecifier as ts.StringLiteral).text;

                if (specifier) {
                    if (specifierRelativeFile.test(specifier)) {
                        found.push({
                            typeOnly: exportDeclaration.isTypeOnly,
                            relativePathReference: true,
                            referencingPath: path,
                            referencedSpecifier: specifier
                        });
                    } else if (specifierNodeModule.test(specifier)) {
                        found.push({
                            typeOnly: exportDeclaration.isTypeOnly,
                            relativePathReference: false,
                            referencingPath: path,
                            referencedSpecifier: specifier
                        });
                    }
                }
            }

            break;
        case ts.SyntaxKind.ImportDeclaration:
            const importDeclaration = node as ts.ImportDeclaration;
            const importClause = importDeclaration.importClause;

            const specifier = (importDeclaration.moduleSpecifier as ts.StringLiteral).text;

            if (specifier) {
                if (specifierRelativeFile.test(specifier)) {
                    found.push({
                        typeOnly: (!!importClause && !importClause.isTypeOnly),
                        relativePathReference: true,
                        referencingPath: path,
                        referencedSpecifier: specifier
                    });
                } else if (specifierNodeModule.test(specifier)) {
                    found.push({
                        typeOnly: (!!importClause && !importClause.isTypeOnly),
                        relativePathReference: false,
                        referencingPath: path,
                        referencedSpecifier: specifier
                    });
                }
            }

            break;
        case ts.SyntaxKind.CallExpression:
            const callExpression = node as ts.CallExpression;

            if ((callExpression.expression.kind === ts.SyntaxKind.ImportKeyword ||
                (callExpression.expression.kind === ts.SyntaxKind.Identifier &&
                    callExpression.expression.getText() === "require")) &&
                callExpression.arguments[0]?.kind === ts.SyntaxKind.StringLiteral) {

                const specifier = (callExpression.arguments[0] as ts.StringLiteral).text;

                if (specifierRelativeFile.test(specifier)) {
                    found.push({
                        typeOnly: false,
                        relativePathReference: true,
                        referencingPath: path,
                        referencedSpecifier: specifier
                    });
                } else if (specifierNodeModule.test(specifier)) {
                    found.push({
                        typeOnly: false,
                        relativePathReference: false,
                        referencingPath: path,
                        referencedSpecifier: specifier
                    });
                } else {
                    await diveDeeper(path, node, found);
                }
            } else {
                await diveDeeper(path, node, found);
            }

            break;
        default:
            await diveDeeper(path, node, found);

            break;
    }
}

const path = "example.ts";

const source = `
import foo from "./foo";
import * as bar from "./bar";
import { buzz } from "./fizz/buzz";

export foo from "./foo";
export * as bar from "./bar";
export { buzz } from "./fizz/buzz";

const whatever = require("whatever");

const stuff = async () => {
    require("whatever");

    const x = await import("xyz");
}
`

const rootNode = ts.createSourceFile(
    path,
    source,
    ts.ScriptTarget.Latest,
    /*setParentNodes */ true
);

const found: FoundReference[] = [];

findAllReferencesNode(path, rootNode, found)
.then(() => { 
    console.log(found); 
});
Run Code Online (Sandbox Code Playgroud)

[
  {
    "typeOnly": true,
    "relativePathReference": true,
    "referencingPath": "example.ts",
    "referencedSpecifier": "./foo"
  },
  {
    "typeOnly": true,
    "relativePathReference": true,
    "referencingPath": "example.ts",
    "referencedSpecifier": "./bar"
  },
  {
    "typeOnly": true,
    "relativePathReference": true,
    "referencingPath": "example.ts",
    "referencedSpecifier": "./fizz/buzz"
  },
  {
    "typeOnly": false,
    "relativePathReference": true,
    "referencingPath": "example.ts",
    "referencedSpecifier": "./bar"
  },
  {
    "typeOnly": false,
    "relativePathReference": true,
    "referencingPath": "example.ts",
    "referencedSpecifier": "./fizz/buzz"
  },
  {
    "typeOnly": false,
    "relativePathReference": false,
    "referencingPath": "example.ts",
    "referencedSpecifier": "whatever"
  },
  {
    "typeOnly": false,
    "relativePathReference": false,
    "referencingPath": "example.ts",
    "referencedSpecifier": "whatever"
  },
  {
    "typeOnly": false,
    "relativePathReference": false,
    "referencingPath": "example.ts",
    "referencedSpecifier": "xyz"
  }
] 
Run Code Online (Sandbox Code Playgroud)

获得引用指定符后,您需要一些基本逻辑将其解析到下一个路径,并递归地使用下一个解析的文件重复探索。