If you are using Typescript and Jest and running into this problem, the answer provided by @prototype will get you halfway there, but you'll then run into an issue where Jest doesn't allow you to use import.meta.
Having now spent an enormous amount of time trying to get both import and require to work in both production and testing, I have arrived at a solution that I want to make sure I share:
Wherever you want to import a legacy package, you need the following:
function legacyRequireImport(path){
if (process.env.NODE_ENV === "test"){
return require(path);
}
const _require = createRequire(import.meta.url);
return _require(path);
}
const someModule = legacyRequireImport("some_module");
Note: the function must be defined in the same file as it is being used. If you export this function and import it whenever you need it, it won't work. The function also cannot be called require, because that is a reserved word in commonJS (what Jest uses).
Now, if you just run that then you will get the following Jest error:
- error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'es2022', 'esnext', 'system', 'node16', or 'nodenext'.
const _require = createRequire(import.meta.url);
In order to fix that, you can install a package called ts-jest-mock-import-meta and add the following to your jest.config:
"transform": {
"^.+\\.(j|t)s?$": ["ts-jest",
{
useESM: false,
diagnostics: {
ignoreCodes: [1343]
},
astTransformers: {
before: [ "node_modules/ts-jest-mock-import-meta"]
}
}
],
}
(this assumes you are using ts-jest, which you probably are if you are using typescript and jest)
You also need to make sure that you do not have a preset set in your jest.config, or else this won't work.
I know this seems insane, and it truly is insane, but this was genuinely the best solution I could find. And it does work. Best of luck.
module.exportsinstead of just export const or something