From c97e4b64a015ef95e65dc308ce00ada1d7993d6d Mon Sep 17 00:00:00 2001 From: Andrew Branch Date: Wed, 28 Jun 2023 15:03:14 -0700 Subject: [PATCH] Fix auto imports in JS files in nodenext (#54817) --- src/services/codefixes/importFixes.ts | 9 +++++-- .../fourslash/autoImportNodeNextJSRequire.ts | 25 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 tests/cases/fourslash/autoImportNodeNextJSRequire.ts 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 +}`]);