Skip to content

Commit c97e4b6

Browse files
authored
Fix auto imports in JS files in nodenext (#54817)
1 parent 6696ecd commit c97e4b6

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/services/codefixes/importFixes.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -803,14 +803,19 @@ function shouldUseRequire(sourceFile: SourceFile, program: Program): boolean {
803803
return getEmitModuleKind(compilerOptions) < ModuleKind.ES2015;
804804
}
805805

806-
// 4. Match the first other JS file in the program that's unambiguously CJS or ESM
806+
// 4. In --module nodenext, assume we're not emitting JS -> JS, so use
807+
// whatever syntax Node expects based on the detected module kind
808+
if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) return true;
809+
if (sourceFile.impliedNodeFormat === ModuleKind.ESNext) return false;
810+
811+
// 5. Match the first other JS file in the program that's unambiguously CJS or ESM
807812
for (const otherFile of program.getSourceFiles()) {
808813
if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue;
809814
if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true;
810815
if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false;
811816
}
812817

813-
// 5. Literally nothing to go on
818+
// 6. Literally nothing to go on
814819
return true;
815820
}
816821

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/// <reference path='fourslash.ts' />
2+
3+
// @module: nodenext
4+
// @allowJs: true
5+
// @checkJs: true
6+
// @noEmit: true
7+
8+
// @Filename: /matrix.js
9+
//// exports.variants = [];
10+
11+
// @Filename: /main.js
12+
//// exports.dedupeLines = data => {
13+
//// variants/**/
14+
//// }
15+
16+
// @Filename: /totally-irrelevant-no-way-this-changes-things-right.js
17+
//// export default 0;
18+
19+
goTo.file("/main.js");
20+
verify.importFixAtPosition([
21+
`const { variants } = require("./matrix")
22+
23+
exports.dedupeLines = data => {
24+
variants
25+
}`]);

0 commit comments

Comments
 (0)