Why is it that different patterns of imports are shown across typescript examples?
;
;
Let us look at how the two examples are compiled to javascript code using tsc
.
First, intialize a project with the following commands:
&&
Fill in the files star.ts
and plain.ts
with the following code:
star.ts
;
React;
plain.ts
;
React;
First, let's compile star.ts
with tsc
and see the output.
star.js
'use strict';
exports.__esModule = true;
;
React;
All good. Now try to compile plain.ts
, and an error will occur.
;
;
The problem occurs because while react
does not have a default export, our typescript file is attempting to default import it. One way of solving this issue might be to use the wildcard(asterisk) import above. Another way is to use the --esModuleInterop
flag. Now let's see how the latter way works, by using that flag in our compiler.
There are no errors, which is a good thing. The compiled file looks like this:
'use strict';
;
exports.__esModule = true;
;
react_1;
One can find out that a wrapper to the require is added. The wrapper provides additional logic, that allows flexible resolution between es6 modules and commonjs modules. It can also be observed that a "default" export or import is, from a commonjs module point of view, the value that corresponds to the key "default"
in the module.exports
object.
AFAIK, javascript packages are usually shipped with the original source code transpiled into using commonjs modules, so the esModuleInterop
flag is a flag that I commonly use in my tsconfig.json
.