Skip to content

Commit 75e3c82

Browse files
refactor: use variable declaration for inactive harmony imports instead of inline undefined
1 parent a55e827 commit 75e3c82

2 files changed

Lines changed: 17 additions & 9 deletions

File tree

lib/dependencies/HarmonyImportSpecifierDependency.js

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"use strict";
77

88
const Dependency = require("../Dependency");
9+
const InitFragment = require("../InitFragment");
910
const Template = require("../Template");
1011
const {
1112
getDependencyUsedByExportsCondition
@@ -342,18 +343,17 @@ HarmonyImportSpecifierDependency.Template = class HarmonyImportSpecifierDependen
342343

343344
// Skip rendering depending when dependency is conditional
344345
if (connection && !connection.isTargetActive(runtime)) {
345-
const {
346-
trimmedRange: [trimmedRangeStart, trimmedRangeEnd]
347-
} = getTrimmedIdsAndRange(ids, dep.range, dep.idRanges, moduleGraph, dep);
348346
const comment = Template.toNormalComment(
349347
`inactive harmony import ${dep.name} ${ids.join(".")}`
350348
);
351-
const expr = `${comment} undefined`;
352-
if (dep.shorthand) {
353-
source.insert(trimmedRangeEnd, `: ${expr}`);
354-
} else {
355-
source.replace(trimmedRangeStart, trimmedRangeEnd - 1, expr);
356-
}
349+
templateContext.initFragments.push(
350+
new InitFragment(
351+
`var ${dep.name} = ${comment} undefined;\n`,
352+
InitFragment.STAGE_HARMONY_IMPORTS,
353+
0,
354+
`inactive harmony import ${dep.name}`
355+
)
356+
);
357357
return;
358358
}
359359
const {

test/configCases/issues/issue-20151/index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,13 @@ it("should correctly handle unused function with same-named local variable", ()
1010
expect(__).toBe("local");
1111
});
1212

13+
it("should declare inactive harmony imports as variables", () => {
14+
const fs = require("fs");
15+
const source = fs.readFileSync(__filename, "utf-8");
16+
// The identifier should remain in the code, but be declared as undefined
17+
expect(source).toContain("var i18n = /* inactive harmony import i18n __ */ undefined;");
18+
expect(source).toMatch(/return i18n\("wtf"\)/);
19+
});
20+
1321
// This ensures unused is not tree-shaken in some configurations
1422
export { unused };

0 commit comments

Comments
 (0)