Breck
Breck

Reputation: 2335

Why does the TypeScript compiler add "default" to my imports?

Here is my code:

import lodash from "lodash"
lodash.sampleSize([1,2], 1);

Here is the generated code:

const lodash_1 = require("lodash");
lodash_1.default.sampleSize([1,2], 1);

In another question I brought up the confusing renaming of lodash to lodash_1, but my question here is why does TypeScript add the "default", when it is very easy to detect that there is no such "default" on the required npm module, in this case lodash?

This is mildly infuriating because when I'm writing my code it only works if I don't have default, and I get all the help from the TypeScript service, but only when I compile it throws errors because "default" does not exist. Why did you add it TypeScript during compile? Why force me to not use default during development and then break during compile? I so sad.

Upvotes: 0

Views: 462

Answers (1)

basarat
basarat

Reputation: 275987

but my question here is why does TypeScript add the "default"

Because that is what x in import x as "x" maps to. Its the default import.

This is mildly infuriating because when I'm writing my code it only works if I don't have default,

It will work if you have "esModuleInterop": true in your tsconfig.json 👍

More

The flag is needed only if you are not using native es modules. Most modules today are no native es modules, and in fact commonjs modules. Hence it is a flag you should have on by default.

Upvotes: 3

Related Questions