Transforming `import.meta` with jest and swc

I've spent a few hours trying to find how this is meant to work with jest and swc. config:
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true
},
"transform": {
"react": {
"runtime": "automatic",
"importSource": "@emotion/react"
}
}
},
"isModule": true
}
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true
},
"transform": {
"react": {
"runtime": "automatic",
"importSource": "@emotion/react"
}
}
},
"isModule": true
}
Jest:
/// <reference types="node" />

const config = JSON.parse(fs.readFileSync(`${process.cwd()}/.swcrc`, 'utf-8'))
delete config.exclude
config.swcrc = false
config.jsc.transform.hidden = {
...config.jsc.transform.hidden,
jest: true
}

/**
* @type { import("jest").Config }
*/
module.exports = {
roots: ['<rootDir>/src/', '<rootDir>/test/'],
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
snapshotSerializers: ['@emotion/jest/serializer'],
testEnvironment: 'jsdom',
testEnvironmentOptions: { url: 'http://localhost/' },
testRegex: '(test|spec).tsx?$',
transform: {
'^.+\\.(t|j)sx?$': ['@swc/jest', config]
}
}
/// <reference types="node" />

const config = JSON.parse(fs.readFileSync(`${process.cwd()}/.swcrc`, 'utf-8'))
delete config.exclude
config.swcrc = false
config.jsc.transform.hidden = {
...config.jsc.transform.hidden,
jest: true
}

/**
* @type { import("jest").Config }
*/
module.exports = {
roots: ['<rootDir>/src/', '<rootDir>/test/'],
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
snapshotSerializers: ['@emotion/jest/serializer'],
testEnvironment: 'jsdom',
testEnvironmentOptions: { url: 'http://localhost/' },
testRegex: '(test|spec).tsx?$',
transform: {
'^.+\\.(t|j)sx?$': ['@swc/jest', config]
}
}
But no matter what I try, I still hit: SyntaxError: Cannot use 'import.meta' outside a module What am I doing wrong here?
3 Replies
Codex
CodexOP2y ago
The same problem happens with:
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true,
"importMeta": true
},
"parser": {
"syntax": "typescript",
"tsx": true,
"decorators": true,
"importMeta": true
},
Codex
CodexOP2y ago
GitHub
Jest with swc, Cannot use 'import.meta' outside a module · Issue ...
Describe the bug I've been adopting the usage of @swc for testing in our Jest test suite for a react application and encountered the issue where when attempting to transpile import.meta.env swc...
Codex
CodexOP2y ago
For anyone stumbling across this, the solution was to write a plugin to handle this explicitly. I've published this: https://github.com/Codex-/swc-plugin-import-meta-env
GitHub
GitHub - Codex-/swc-plugin-import-meta-env
Contribute to Codex-/swc-plugin-import-meta-env development by creating an account on GitHub.

Did you find this page helpful?