esModuleInterop flag set, still getting default import error

Viewed 3672

I have a React project using TypeScript, and in the main tsx file, the import React from 'react' line works fine. However in my test file, it's still triggering the TS1259 error. I'm guessing there is something funky with my TS/Jest/Babel config, but can't seem to pin it down.

Anybody know what the issue is?

tsconfig.json

{
    "compilerOptions": {
        "allowSyntheticDefaultImports": true,
        "target": "ES2019",
        "moduleResolution": "node",
        "module": "ESNext",
        "allowJs": true,
        "noEmit": true,
        "strict": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "strictNullChecks": true,
        "jsx": "react",
        "baseUrl": "./",
        "types": []
    },
    "include": [
        "index.d.ts",
        "src/*.ts",
        "src/*.tsx",
        "src/**/*.ts",
        "src/**/*.tsx"
    ]
}

jest.config.js

module.exports = {
    collectCoverageFrom: ['src/**/*.{ts,tsx}', '!src/index.ts'],
    moduleNameMapper: {'^.+\\.s?css$': 'identity-obj-proxy'},
    transform: {'^.+\\.tsx?$': 'babel-jest'},
    testRegex: '/__tests__/.*\\.test\\.tsx?$',
    testURL: 'http://localhost',
    setupFilesAfterEnv: ['<rootDir>/__tests__/setup.ts'],
    setupFiles: [],
    testPathIgnorePatterns: [
        '__snapshots__',
        '__mocks__',
        '<rootDir>/scripts',
    ],
};

Error message in Jest test file

Error message in Jest test file

No error in main component file

No error in main component file

1 Answers

TypeScript determines which files are considered part of your project based on a variety of options specified in your tsconfig.json.

If you use the "include" and/or "files" properties to explicitly indicate these files, only those files which match the paths and patterns specified therein, together with those they reference either directly or transitively, are part of the project.

Any "compilerOptions", such as "esModuleInterop", apply only to these files.

As you have specified

"include": [
  "index.d.ts",
  "src/*.ts",
  "src/*.tsx",
  "src/**/*.ts",
  "src/**/*.tsx"
]

If your tests are not under the src directory, they will not be considered part of your project and your compiler options will not be applied to them.

You can verify which files are included in your project on the command line by running

$ tsc --listFilesOnly

If you have multiple tsconfig files, which is often the case especially in newer projects, you can specify the project as well with the --project option

For example

$ tsc --listFilesOnly --project ./tsconfig.app.json
Related