Search code examples
typescriptwebpackjestjsts-jest

TS-Jest fails to recognize webpack Define plugin variables


I'm trying to run (TS)-Jest in my application that contains a few global variables that get injected at build time by Webpack (with Define Plugin)

For example:

console.log(`Current build: ${__BUILD_VERSION}`)

The variable __BUILD_VERSION is not defined anywhere in the code so TS complains about it.

Here's the output when attempting to run Jest:

src/.../.../file.ts - error TS2304: Cannot find name '__BUILD_VERSION'.

I have tried defining them as Jest "globals" with no luck. Apparently is a Typescript error so maybe i should try something in tsconfig.json?


Solution

  • If you need this variables when running jest then set globals flag flag in your jest.config (or in package.json if you using it for config):

    "globals": {
      "__BUILD_VERSION": 123,
      "YOUR_OTHER_VARIABLE": 'foo'
    }
    

    If you need to fix Typescript then you need to declare that variable somewhere, for example create globals.d.ts file and declare it there:

    declare const __BUILD_VERSION: string;