From 2b50eef52bac21b5624a569ecf70fd686f273a7c Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sun, 6 Jun 2021 22:55:34 +0200 Subject: [PATCH] Fix for CJSImportProcessor not using interop helper for aliased default imports (#619) --- src/CJSImportProcessor.ts | 15 ++++++++++++--- test/imports-test.ts | 17 +++++++++++++++++ test/typescript-test.ts | 2 +- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/src/CJSImportProcessor.ts b/src/CJSImportProcessor.ts index 10d1248c..3b948c28 100644 --- a/src/CJSImportProcessor.ts +++ b/src/CJSImportProcessor.ts @@ -178,7 +178,7 @@ export default class CJSImportProcessor { private preprocessImportAtIndex(index: number): void { const defaultNames: Array = []; const wildcardNames: Array = []; - let namedImports: Array = []; + const namedImports: Array = []; index++; if ( @@ -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)) { diff --git a/test/imports-test.ts b/test/imports-test.ts index bbf47959..7986cbc0 100644 --- a/test/imports-test.ts +++ b/test/imports-test.ts @@ -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( ` diff --git a/test/typescript-test.ts b/test/typescript-test.ts index 62cacd19..157de499 100644 --- a/test/typescript-test.ts +++ b/test/typescript-test.ts @@ -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';