[SWC plugin] workaround for jest
This is a SWC plugin to handle jest compatibility issues.
This SWC plugin should be used with @swc/jest
.
usage
install
npm i -D jest @swc/core @swc/jest jest_workaround
// jest.config.js
const fs = require("node:fs");
const swcrc = JSON.parse(fs.readFileSync(".swcrc", "utf8"));
// If you have other plugins, change this line.
((swcrc.jsc ??= {}).experimental ??= {}).plugins = [["jest_workaround", {}]];
module.exports = {
transform: {
"^.+\\.(t|j)sx?$": ["@swc/jest", swcrc],
},
};
Make sure that module.type
is commonjs
in your .swcrc
since this plugin does not touch non-workaround parts, such as import statements.
FAQ
- When do I need this?
The swc-transformed CJS is compliant with the ESM specification. This means that exports is immutable.
I need to use swc to get transformed code which conforms to the ESM specification. But I need to use jest in a CJS environment to test it.
The immutable exports is difficult to use for jest testing. This plugin will transform the export statement into mutable exports.
- Do I have a better choice?
Yes.
If I can run jest in an ESM environment, then I don't even need swc, or just use swc to transform TypeScript syntax.
There may be some issues with running jest in ESM, but they will be resolved over time. Tracked by facebook/jest#9430.
Or, I don't need the behavior of ESM. I can get the CJS behavior of exports by using the CJS syntax.
CJS specific syntax
exports.foo = function foo(){
return 42;
}
CTS(CJS in TypeScript) syntax
export = {
foo: function foo(){
return 42;
}
}
Notes:
- ESM style export means immutable exports when transformed into CJS
- ESM style import means hoisted require when transformed into CJS