Reputation: 40064
Trying to use the file-type module which is pure ESM in a TS project but my jest fails. I have set the ESM options as indicated here but still get a SyntaxError: Cannot use import statement outside a module
error.
I have made a sandbox here.
Summary of my code:
import { fileTypeFromBuffer } from "file-type";
Jest config:
export default {
testEnvironment: "jest-environment-node",
globals: {
extensionsToTreatAsEsm: [".ts"],
"ts-jest": {
useESM: true,
},
},
transform: {
"^.+\\.(ts|tsx|js|jsx)?$": "ts-jest",
//"^.+\\.tsx?$": "ts-jest",
},
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
},
preset: "ts-jest",
//preset: 'ts-jest/presets/default-esm' // or other ESM presets
};
TSConfig:
{
"extends": "@tsconfig/node14/tsconfig.json",
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"lib": ["es2018"],
"declaration": true,
"strict": true,
"strictNullChecks": true,
"alwaysStrict": true,
//importsNotUsedAsValues
// "noImplicitAny": false,
"noImplicitReturns": false,
"noImplicitThis": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"noEmit": true,
"noFallthroughCasesInSwitch": false,
"inlineSourceMap": true,
"inlineSources": true,
"experimentalDecorators": true,
"strictPropertyInitialization": false,
// "typeRoots": ["./node_modules/@types"]
"resolveJsonModule": true,
"outDir": "dist",
"baseUrl": ".",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Any ideas?
Upvotes: 10
Views: 4319
Reputation: 31805
You have to tell Jest to transform those ESM bundled libraries with the transformIgnorePatterns
option.
This options specifies the ignored paths and it defaults to ["/node_modules/", "\\.pnp\\.[^\\\/]+$"]
which explains why the libraries are not being transformed.
The most straightforward solution is to set an empty array:
transformIgnorePatterns: []
But you could also set a more fine-grained config to exclude everything except some particular libraries, like in the regex example of the docs.
Also, add the "allowJs": true
option in the TypeScript configuration.
Upvotes: 4