Skip to content

Commit

Permalink
Fix for CJSImportProcessor not using interop helper for aliased defau…
Browse files Browse the repository at this point in the history
…lt imports (#619)
  • Loading branch information
Rugvip authored Jun 6, 2021
1 parent 805cd66 commit 2b50eef
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/CJSImportProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ export default class CJSImportProcessor {
private preprocessImportAtIndex(index: number): void {
const defaultNames: Array<string> = [];
const wildcardNames: Array<string> = [];
let namedImports: Array<NamedImport> = [];
const namedImports: Array<NamedImport> = [];

index++;
if (
Expand Down Expand Up @@ -212,8 +212,17 @@ export default class CJSImportProcessor {
}

if (this.tokens.matches1AtIndex(index, tt.braceL)) {
index++;
({newIndex: index, namedImports} = this.getNamedImports(index));
const result = this.getNamedImports(index + 1);
index = result.newIndex;

for (const namedImport of result.namedImports) {
// Treat {default as X} as a default import to ensure usage of require interop helper
if (namedImport.importedName === "default") {
defaultNames.push(namedImport.localName);
} else {
namedImports.push(namedImport);
}
}
}

if (this.tokens.matchesContextualAtIndex(index, ContextualKeyword._from)) {
Expand Down
17 changes: 17 additions & 0 deletions test/imports-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,23 @@ var _moduleName = require('moduleName');
);
});

it("transforms named default import access to property access", () => {
assertResult(
`
import {default as foo} from 'my-module';
foo.test();
test.foo();
`,
`"use strict";${IMPORT_DEFAULT_PREFIX}
var _mymodule = require('my-module'); var _mymodule2 = _interopRequireDefault(_mymodule);
_mymodule2.default.test();
test.foo();
`,
);
});

it("transforms named import access to property access", () => {
assertResult(
`
Expand Down
2 changes: 1 addition & 1 deletion test/typescript-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ describe("typescript transform", () => {
assertTypeScriptResult(
`
import A from 'a';
import B from 'b';
import {default as B} from 'b';
import 'c';
import D from 'd';
import 'd';
Expand Down

0 comments on commit 2b50eef

Please sign in to comment.