diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 6e7f9916748..fb6b5df8fcc 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -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; } diff --git a/tests/cases/fourslash/autoImportNodeNextJSRequire.ts b/tests/cases/fourslash/autoImportNodeNextJSRequire.ts new file mode 100644 index 00000000000..f5990cd92c8 --- /dev/null +++ b/tests/cases/fourslash/autoImportNodeNextJSRequire.ts @@ -0,0 +1,25 @@ +/// + +// @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 +}`]);