Implement `getCacheKey`
What & Why
- Now,
jest-previewhasn't implemented getCacheKey forcss,fileandfileCRAtransformer. https://github.com/nvh95/jest-preview/blob/6ce35ca37d6c9de5fc72b05ce433cb83b10b0538/src/preconfigTransform/css.ts#L1-L8 - The reason is that we are not very deeply understand the benefit of
getCacheKey. The [docs]((https://jestjs.io/docs/code-transformation) itself is not very detail. But we know it boosts the performance when running Jest since we're caching the transformed files.
How
- We can find
@swc/jestimplementedgetCacheKey. Let's see how they do that. https://github.com/swc-project/jest/blob/17cf883b46c050a485975d8ce96a05277cf6032f/index.ts#L37-L52 - There are some related PRs as well https://github.com/swc-project/jest/pull/32 https://github.com/swc-project/jest/pull/76
- We need to benchmark to see how much users' time
getCacheKeysaves.
As I observe and guess, if we do not implement getCacheKey, Jest automatically cache using return value in the transformation.
For e.g: If our css transform a css file to
const relativeCssPath = "/demo/App.css";
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = relativeCssPath;
document.body.appendChild(link);
module.exports = JSON.stringify(relativeCssPath);
This whole file content will be used as the key for caching.
So what is the point of implementing getCacheKey? To get a shorter key? Do we need to do that?
How to see the cache key by yourself
- Run
jest --clearCacheto see where the cache located. For e.g, on mac:/private/var/folders/hg/cg39z3hd4gv3grbrd08524gh0000gp/T/jest_dy -
cdto that project and explore
My hypothesis: If we do not explicitly implement getCacheKey. It will use src and filename as cache key.
So, we should add transformer file content into account. So each time we upgrade the transformer. The Jest cache get cleared.