swc-node
swc-node copied to clipboard
@swc-node/jest ReferenceError: React is not defined
EDIT: I don't think react runtime is supported by @swc-node
at all.@swc-node/loader
works in webpack but the bundle produced does not have the react runtime.
Below is the original issue:
my project was using @swc/jest
and a .swcrc
like this and jest works fine:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"dynamicImport": true,
"privateMethod": true,
"functionBind": true,
"exportDefaultFrom": true,
"exportNamespaceFrom": true,
"decorators": true,
"decoratorsBeforeExport": true,
"topLevelAwait": true,
"importMeta": true
},
"transform": {
"react": {
"runtime": "automatic"
}
},
"target": "es5",
"loose": false,
"externalHelpers": false,
"keepClassNames": false
}
}
I want to move to @swc-node/jest
since I already have a tsconfig.json
and I don't see a need to maintain both the .swcrc
and tsconfig.json
.
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"noFallthroughCasesInSwitch": true,
"suppressImplicitAnyIndexErrors": true,
"noImplicitAny": false,
"sourceMap": true,
},
"include": [
"src"
]
}
I changed jest config from "^.+\\.(t|j)sx?$": "@swc/jest",
to "^.+\\.(t|j)sx?$": "@swc-node/jest",
and got error ReferenceError: React is not defined
. I copied the configs in .swcrc
from above into jest config and still got the same error. It seems the react runtime configuration is not applied by @swc-node/jest
but am applied by @swc/jest
?
I'm building my react lib with Rollup, and just using @swc/jest for the tests:
const config = {
...config,
transform: {
'^.+\\.(t|j)sx?$': [
'@swc/jest',
{
jsc: {
transform: {
react: {
runtime: 'automatic',
},
},
},
},
],
},
};
So there's no need to have a .swcrc
in this case.
Reference
https://github.com/swc-project/swc-node/issues/635#issuecomment-1070766669 was key for me. For some reason it didn't work in .swcrc
but worked fine when passed directly into the jest config. 🤷🏼♂️