How does module resolution in TypeScript work for

2020-08-12 09:34发布

问题:

While using jest on its own the corresponding typescript definitions got detected right after installing @types/jest.

I then started to implement integration tests with cypress. Since cypress is using mocha, I now incorrectly see references of mocha type definitions inside my jest tests. In fact, a number of overlapping type definitions are detected. For instance, describe seems to be defined in a number of files. I even tried to implement my own typing for describe pointing to jest. Unfortunately, every single time mocha "wins".

How can I specify the order of precedence when multiple definitions are detected by the typescript compiler?

My tsconfig.json looks like this:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [ "dom", "dom.iterable", "esnext" ],
        "types": [ "jest", "mocha" ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "strictNullChecks": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": false,
        "noEmit": true,
        "jsx": "preserve"
    },
    "include": [ "src/**/*" ]
}

However, I also tried the following:

{
    "compilerOptions": {
        "target": "es5",
        "lib": [ "dom", "dom.iterable", "esnext" ],
        "typeRoots": [ "./node_modules/@types", "./src/types" ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "strictNullChecks": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": false,
        "noEmit": true,
        "jsx": "preserve"
    },
    "include": [ "src/**/*" ]
}

In both cases mocha is being chosen. How can I switch the type for "describe & co." to jest?

回答1:

CompilerOptions.types allow you to restrict the typings you want to be available in the scope(folder)

You can try the following: Create a top level tsconfig.json with CompilerOptions.types = []

Inside test folder create tsconfig.json and choose jest typings CompilerOptions.types = ['jest']

Similarly inside integration folder, create tsconfig.json and choose mocha typings CompilerOptions.types = ['mocha']