typescript - How do I import a default export when esModuleInterop is false? - Stack Overflow

admin2025-05-01  1

I'm trying to construct a class from an upstream typescript project where they've set esModuleInterop: false on their tsconfig.json.

import DefaultClass from '@upstream/lib/DefaultClass'

console.log(DefaultClass)
const defaultClass = new DefaultClass()

This compiles correctly with tsc but if I try to run it with tsx I get the error DefaultClass is not a constructor. Looking at the output of the log statement I'm seeing something like this

{ loadDefaults: [Function loadDefaults], default: [class DefaultClass] }

If I change the code above to use new DefaultClass.default() it runs with tsx but then tsc and the language server will scream at me that the property default does not exist!

Is there some work around that I must do to bring tsc and tsx inline? Why is tsx not respecting the default exports?


my tsconfig.json for reference

{
  "compilerOptions": {
    "target": "es2022",
    "module": "es2022",
    "rootDir": "src",
    "outDir": "./out",
    "esModuleInterop": true,
    "moduleResolution":"node",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "skipLibCheck": true
  }
}

The tsconfig.json of the upstream project says esModuleInterop: false but I'm seeing this in the javascript files

"use strict"
Object.defaultProperty(exports, "__esModule", { value: true });
// ...
class DefaultClass {
// ...
}
exports.default = DefaultClass;
function loadDefaults(path) {
// ...
}
exports.loadDefaults = loadDefaults;
转载请注明原文地址:http://www.anycun.com/QandA/1746102448a91699.html