Skip to content

esModuleInterop generates different code for "import foo" and "import { default as foo }" #21541

@gustavderdrache

Description

@gustavderdrache

TypeScript Version: 2.7.1, 2.8.0-dev.20180201

Search Terms: default import, interop, esm

Code

import foo from './foo';
import { default as bar } from './bar';

console.log(foo, bar);

Expected behavior:

Both imports should generate the same __importDefault(require(...)) calls.

Actual behavior:

Only the import foo syntax generates a synthetic default import. import { default as foo } does not. My understanding of the spec (it looks like the "Import Forms Mappings to ImportEntry Records" table in §15.2.1.16 is the most relevant citation) is that both of these should access the module's "default" property and thus trigger the same synthetic default import behavior.

var foo_1 = __importDefault(require("./foo"));
var foo_2 = require("./bar"); // ???

console.log(foo["default"], bar["default"]);

Playground Link: N/A (The playground doesn't appear to be running 2.7 yet)

Related Issues: N/A (Couldn't find any)

Other notes:

This behavior is present in Babel 6.

Babel 7, however, generates code in line with my expectations (see @babel/babel-helper-module-imports:

var _foo = _interopRequireDefault(require("./foo"));
var _bar = _interopRequireDefault(require("./bar"));

console.log(_foo.default, _bar.default);

The module @std/esm generates the same code in both cases. I extracted this from the cached files it generated:

let foo; _d40‍.w('./foo',[["default",function(v){foo=v}]]);
let bar; _d40‍.w('./bar',[["default",function(v){bar=v}]]);

console.log(foo, bar);

Rollup generates a different default interop helper (it doesn't look for __esModule), but it agrees with Babel 7 and @std/esm:

var foo = _interopDefault(require('foo'));
var bar = _interopDefault(require('bar'));

console.log(foo, bar);

Webpack also does the same thing, albeit with slightly more verbosity:

/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foo__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foo___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__foo__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__bar__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__bar___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1__bar__);

console.log(__WEBPACK_IMPORTED_MODULE_0__foo___default.a, __WEBPACK_IMPORTED_MODULE_1__bar___default.a);

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions