jestjs/jest

[Feature]: Support ability to recompute cache key for certain files more often

Open

#14,630 创建于 2023年10月20日

在 GitHub 查看
 (14 评论) (0 反应) (0 负责人)TypeScript (45,361 star) (6,653 fork)batch import
:rocket: Feature RequestHelp WantedPinned

描述

🚀 Feature Proposal

The ability for TransformerFactory's getCacheKey and getCacheKeyAsync to notify jest if the key has changed even if the file text hasn't.

Specifically:

  • Add the ability for getting a cache key to be returned with some extra metadata.
  • Namely, an object with the following shape:
    export interface CacheKey {
      key: string;
      nextComputation?: "any-file" | "file";
    }
    
  • The default for nextComputation is "file" which means the current implementation, and just returning a string would also continue to mean "any-file"
  • "any-file" would mean that this cache key would get recomputed the next time any file gets saved. This would be a transient field, meaning that a cache key getter could switch between "file" and "any-file"

Motivation

Some typescript build systems (most notably esbuild) have support for a glob style import which transforms the import into a list of normal imports and then combines them into an array for use.

This means that if a new file is introduced matching the glob then the transformation should be redone automatically. The proposed feature would allow advanced jest users to implement this for themselves.

Example

New possible implementation (with this new feature):

Added features:

  • The ability to return not just a cache key, but also some meta data
const globImportTransformer = {
  getCacheKey: (sourceText, sourcePath, options) => {
    const fileMatching = globImportRegex.exec(sourceText);
    const { dynamicImportGlob } = fileMatching?.groups ?? {};

    const globImportedFiles = dynamicImportGlob
      ? discoverGlobFilesSync(sourcePath, dynamicImportGlob)
      : [];

    return {
      key: computeCacheKey(globImportedFiles, sourceText, sourcePath, options),
      nextCheck: dynamicImportGlob ? "any-file" : "file",
    };
  },
   ...
};

Pitch

It is not currently possible to have this sort of back channel notification within jest, the current workaround for users is to manually trigger a getCacheKey(Async) call by touching the file that includes the glob.

贡献者指南