Do I ever need explicit allowSyntheticDefaultImports if esModuleInterop is true configuring TypeScript transpilation?

Konrad Viltersten picture Konrad Viltersten · Sep 30, 2018 · Viewed 19.6k times · Source

I need confirmation on the following theory. According to TS docs, there are two options that can be set in tsconfig.json.

  1. --allowSyntheticDefaultImports: Allow default imports from modules with no default export. This does not affect code emit, just typechecking.

  2. --esModuleInterop: Emit __importStar and __importDefault helpers for runtime babel ecosystem compatibility and enable --allowSyntheticDefaultImports for typesystem compatibility.

When I google around, I see both being set to true (at least in regard to the behavior I'm aiming at). However, as far I understand the docs, TS and transpilation to JS, it makes no sense to use them both.

The way I figure, I might use the latter only and entirely remove the former. However, being cautious and humble, I'm not entirely certain and worry that I'm doing something less bright without realizing it at the moment.

I fear that it's something inappropriate that's going to bite me in the donkey later on causing hours of lamenting and hair-pulling while desperately trouble-shooting. The basis for the skepticism is that both options are available, so I'm inferring that there are four cases where all the combinations (true/false etc.) are required but I can't imagine which they are.

Is it entirely safe to skip --allowSyntheticDefaultImports if --esModuleInterop: true in compilerOptions? ANd if so, why do we have that option?

Bonus question: when is it required with all the four combinations (true/false) for those two options?

Answer

Burt_Harris picture Burt_Harris · Oct 8, 2018

If you mean can you leave allowSyntheticDefaultImports undefined and define only esModuleInterop, the answer should be YES moving forward, but there has been an issue with this. PR #26866 seems to be a fix, only merged September 17, so it there may be some risk in the short term.

As why both exist, I believe these were both a part of addressing compatibility issues with imports of Babel-transpiled modules, the original PR added the allowSyntheticDefaultImports option to certain compile-time messages, but in practice didn't address the runtime behavior of the imports. So --esModuleInterop was added later. See TypeScript-Handbook/#816 for discussion of how to update the docs...