'What is the point of Jest's createTransformer method in its *Transformer interface?

I have been looking into/debugging code transformation related issues in Jest for the last day and a recurring theme is that the SyncTransformer#createTransformer method is a constant source of surprise and it is not really documented why it exists.

The SyncTransformer interface only has a single field one has to implement: process. But it seems that if one implements createTransformer those other methods will not be used: instead Jest seems to create a new transformer using createTransformer, which caused me to lose a few hairs until I figured what was going on. This behaviour is not documented either.

The babel-jest source for Jest 27.



Solution 1:[1]

I filed a documentation bug issue with Jest after I could see that the behavior was not mirrored in the docs, which I subsequently fixed by updating the types and docs for code transformation.

The rules for this is basically like follows:

  • if createTransformer exists as an export, then jest-transform will use that to create a transformer dynamically and not use any of the other exports
  • if the transformer is imported using import (and not require) it will try to use processAsync and fall back to process if the async version does not exist

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oligofren