Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for CJSImportProcessor not using interop helper for aliased default imports #619

Merged
merged 1 commit into from
Jun 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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