Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 29 additions & 8 deletions src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ namespace ts.codefix {
const symbol = checker.getMergedSymbol(skipAlias(exportedSymbol, checker));
const exportInfos = getAllReExportingModules(sourceFile, symbol, moduleSymbol, symbolName, host, program, useAutoImportProvider);
const preferTypeOnlyImport = !!usageIsTypeOnly && compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error;
const useRequire = shouldUseRequire(sourceFile, compilerOptions);
const useRequire = shouldUseRequire(sourceFile, program);
const fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, /*position*/ undefined, preferTypeOnlyImport, useRequire, host, preferences);
addImport({ fixes: [fix], symbolName });
}
Expand Down Expand Up @@ -211,7 +211,7 @@ namespace ts.codefix {
): { readonly moduleSpecifier: string, readonly codeAction: CodeAction } {
const compilerOptions = program.getCompilerOptions();
const exportInfos = getAllReExportingModules(sourceFile, exportedSymbol, moduleSymbol, symbolName, host, program, /*useAutoImportProvider*/ true);
const useRequire = shouldUseRequire(sourceFile, compilerOptions);
const useRequire = shouldUseRequire(sourceFile, program);
const preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && !isSourceFileJS(sourceFile) && isValidTypeOnlyAliasUseSite(getTokenAtPosition(sourceFile, position));
const moduleSpecifier = first(getNewImportInfos(program, sourceFile, position, preferTypeOnlyImport, useRequire, exportInfos, host, preferences)).moduleSpecifier;
const fix = getImportFixForSymbol(sourceFile, exportInfos, moduleSymbol, symbolName, program, position, preferTypeOnlyImport, useRequire, host, preferences);
Expand Down Expand Up @@ -362,10 +362,31 @@ namespace ts.codefix {
});
}

function shouldUseRequire(sourceFile: SourceFile, compilerOptions: CompilerOptions): boolean {
return isSourceFileJS(sourceFile)
&& !sourceFile.externalModuleIndicator
&& (!!sourceFile.commonJsModuleIndicator || getEmitModuleKind(compilerOptions) < ModuleKind.ES2015);
function shouldUseRequire(sourceFile: SourceFile, program: Program): boolean {
// 1. TypeScript files don't use require variable declarations
if (!isSourceFileJS(sourceFile)) {
return false;
}

// 2. If the current source file is unambiguously CJS or ESM, go with that
if (sourceFile.commonJsModuleIndicator && !sourceFile.externalModuleIndicator) return true;
if (sourceFile.externalModuleIndicator && !sourceFile.commonJsModuleIndicator) return false;

// 3. If there's a tsconfig/jsconfig, use its module setting
const compilerOptions = program.getCompilerOptions();
if (compilerOptions.configFile) {
return getEmitModuleKind(compilerOptions) < ModuleKind.ES2015;
}

// 4. 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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// 5. Literally nothing to go on
// 5. Literally nothing to go on, why not zoidberg?

return true;
}

function getNewImportInfos(
Expand Down Expand Up @@ -445,7 +466,7 @@ namespace ts.codefix {
const symbol = checker.getAliasedSymbol(umdSymbol);
const symbolName = umdSymbol.name;
const exportInfos: readonly SymbolExportInfo[] = [{ moduleSymbol: symbol, importKind: getUmdImportKind(sourceFile, program.getCompilerOptions()), exportedSymbolIsTypeOnly: false }];
const useRequire = shouldUseRequire(sourceFile, program.getCompilerOptions());
const useRequire = shouldUseRequire(sourceFile, program);
const fixes = getFixForImport(exportInfos, symbolName, isIdentifier(token) ? token.getStart(sourceFile) : undefined, /*preferTypeOnlyImport*/ false, useRequire, program, sourceFile, host, preferences);
return { fixes, symbolName };
}
Expand Down Expand Up @@ -497,7 +518,7 @@ namespace ts.codefix {

const compilerOptions = program.getCompilerOptions();
const preferTypeOnlyImport = compilerOptions.importsNotUsedAsValues === ImportsNotUsedAsValues.Error && isValidTypeOnlyAliasUseSite(symbolToken);
const useRequire = shouldUseRequire(sourceFile, compilerOptions);
const useRequire = shouldUseRequire(sourceFile, program);
const exportInfos = getExportInfos(symbolName, getMeaningFromLocation(symbolToken), cancellationToken, sourceFile, program, useAutoImportProvider, host);
const fixes = arrayFrom(flatMapIterator(exportInfos.entries(), ([_, exportInfos]) =>
getFixForImport(exportInfos, symbolName, symbolToken.getStart(sourceFile), preferTypeOnlyImport, useRequire, program, sourceFile, host, preferences)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@

goTo.file("/c.js");
verify.importFixAtPosition([
`import { foo } from "./b";
`const { foo } = require("./b");

foo`]);

This file was deleted.

19 changes: 19 additions & 0 deletions tests/cases/fourslash/importNameCodeFix_jsCJSvsESM1.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/// <reference path="fourslash.ts" />
// @allowJs: true
// @checkJs: true

// @Filename: types/dep.d.ts
//// export declare class Dep {}

// @Filename: index.js
//// Dep/**/

// @Filename: util.js
//// import fs from 'fs';


// When current file has no imports/requires, look at other JS files
goTo.marker("");
verify.importFixAtPosition([`import { Dep } from "./types/dep";

Dep`]);
22 changes: 22 additions & 0 deletions tests/cases/fourslash/importNameCodeFix_jsCJSvsESM2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/// <reference path="fourslash.ts" />
// @allowJs: true
// @checkJs: true

// @Filename: types/dep.d.ts
//// export declare class Dep {}

// @Filename: index.js
//// Dep/**/

// @Filename: util1.ts
//// import fs from 'fs';

// @Filename: util2.js
//// const fs = require('fs');


// TypeScript files don't count as indicators of import style for JS
goTo.marker("");
verify.importFixAtPosition([`const { Dep } = require("./types/dep");

Dep`]);
24 changes: 24 additions & 0 deletions tests/cases/fourslash/importNameCodeFix_jsCJSvsESM3.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/// <reference path="fourslash.ts" />
// @allowJs: true
// @checkJs: true

// @Filename: types/dep.d.ts
//// export declare class Dep {}

// @Filename: index.js
//// import fs from 'fs';
//// const path = require('path');
////
//// Dep/**/

// @Filename: util2.js
//// export {};


// When current file has both imports and requires, get import style from other files
goTo.marker("");
verify.importFixAtPosition([`import fs from 'fs';
import { Dep } from './types/dep';
const path = require('path');

Dep`]);
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// @allowJs: true
// @checkJs: true

// @Filename: blah.js
// @Filename: blah.ts
////export default class Blah {}
////export const Named1 = 0;
////export const Named2 = 1;
Expand Down