jestjs/jest

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

Open

#14,630 opened on Oct 20, 2023

View on GitHub
聽(14 comments)聽(0 reactions)聽(0 assignees)TypeScript聽(45,361 stars)聽(6,653 forks)batch import
:rocket: Feature RequestHelp WantedPinned

Description

馃殌 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.

Contributor guide

[Feature]: Support ability to recompute cache key for certain files more often 路 jestjs/jest#14630 | Good First Issue