@@ -5,7 +5,9 @@ namespace ts {
5
5
const checker = program . getDiagnosticsProducingTypeChecker ( ) ;
6
6
const diags : Diagnostic [ ] = [ ] ;
7
7
8
- if ( sourceFile . commonJsModuleIndicator && ( programContainsEs6Modules ( program ) || compilerOptionsIndicateEs6Modules ( program . getCompilerOptions ( ) ) ) ) {
8
+ if ( sourceFile . commonJsModuleIndicator &&
9
+ ( programContainsEs6Modules ( program ) || compilerOptionsIndicateEs6Modules ( program . getCompilerOptions ( ) ) ) &&
10
+ containsTopLevelCommonjs ( sourceFile ) ) {
9
11
diags . push ( createDiagnosticForNode ( getErrorNodeFromCommonJsIndicator ( sourceFile . commonJsModuleIndicator ) , Diagnostics . File_is_a_CommonJS_module_it_may_be_converted_to_an_ES6_module ) ) ;
10
12
}
11
13
@@ -61,6 +63,29 @@ namespace ts {
61
63
return diags . concat ( checker . getSuggestionDiagnostics ( sourceFile ) ) ;
62
64
}
63
65
66
+ // convertToEs6Module only works on top-level, so don't trigger it if commonjs code only appears in nested scopes.
67
+ function containsTopLevelCommonjs ( sourceFile : SourceFile ) : boolean {
68
+ return sourceFile . statements . some ( statement => {
69
+ switch ( statement . kind ) {
70
+ case SyntaxKind . VariableStatement :
71
+ return ( statement as VariableStatement ) . declarationList . declarations . some ( decl =>
72
+ isRequireCall ( propertyAccessLeftHandSide ( decl . initializer ) , /*checkArgumentIsStringLiteralLike*/ true ) ) ;
73
+ case SyntaxKind . ExpressionStatement : {
74
+ const { expression } = statement as ExpressionStatement ;
75
+ if ( ! isBinaryExpression ( expression ) ) return isRequireCall ( expression , /*checkArgumentIsStringLiteralLike*/ true ) ;
76
+ const kind = getSpecialPropertyAssignmentKind ( expression ) ;
77
+ return kind === SpecialPropertyAssignmentKind . ExportsProperty || kind === SpecialPropertyAssignmentKind . ModuleExports ;
78
+ }
79
+ default :
80
+ return false ;
81
+ }
82
+ } ) ;
83
+ }
84
+
85
+ function propertyAccessLeftHandSide ( node : Expression ) : Expression {
86
+ return isPropertyAccessExpression ( node ) ? propertyAccessLeftHandSide ( node . expression ) : node ;
87
+ }
88
+
64
89
function importNameForConvertToDefaultImport ( node : AnyValidImportOrReExport ) : Identifier | undefined {
65
90
switch ( node . kind ) {
66
91
case SyntaxKind . ImportDeclaration :
0 commit comments