jestjs/jest

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

Open

#14.630 aperta il 20 ott 2023

Vedi su GitHub
 (14 commenti) (0 reazioni) (0 assegnatari)TypeScript (6653 fork)batch import
:rocket: Feature RequestHelp WantedPinned

Metriche repository

Star
 (45.361 star)
Metriche merge PR
 (Merge medio 11g 22h) (11 PR mergiate in 30 g)

Descrizione

🚀 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.

Guida contributor