Fix auto imports in JS files in nodenext (#54817)

This commit is contained in:
Andrew Branch
2023-06-28 15:03:14 -07:00
committed by GitHub
parent 6696ecd37e
commit c97e4b64a0
2 changed files with 32 additions and 2 deletions

View File

@@ -803,14 +803,19 @@ function shouldUseRequire(sourceFile: SourceFile, program: Program): boolean {
return getEmitModuleKind(compilerOptions) < ModuleKind.ES2015;
}
// 4. Match the first other JS file in the program that's unambiguously CJS or ESM
// 4. In --module nodenext, assume we're not emitting JS -> JS, so use
// whatever syntax Node expects based on the detected module kind
if (sourceFile.impliedNodeFormat === ModuleKind.CommonJS) return true;
if (sourceFile.impliedNodeFormat === ModuleKind.ESNext) return false;
// 5. Match the first other JS file in the program that's unambiguously CJS or ESM
for (const otherFile of program.getSourceFiles()) {
if (otherFile === sourceFile || !isSourceFileJS(otherFile) || program.isSourceFileFromExternalLibrary(otherFile)) continue;
if (otherFile.commonJsModuleIndicator && !otherFile.externalModuleIndicator) return true;
if (otherFile.externalModuleIndicator && !otherFile.commonJsModuleIndicator) return false;
}
// 5. Literally nothing to go on
// 6. Literally nothing to go on
return true;
}

View File

@@ -0,0 +1,25 @@
/// <reference path='fourslash.ts' />
// @module: nodenext
// @allowJs: true
// @checkJs: true
// @noEmit: true
// @Filename: /matrix.js
//// exports.variants = [];
// @Filename: /main.js
//// exports.dedupeLines = data => {
//// variants/**/
//// }
// @Filename: /totally-irrelevant-no-way-this-changes-things-right.js
//// export default 0;
goTo.file("/main.js");
verify.importFixAtPosition([
`const { variants } = require("./matrix")
exports.dedupeLines = data => {
variants
}`]);