Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

--defaultIsModuleExports and --allowRequireESM #58526

Closed
Closed
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
21 changes: 17 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
addSyntheticLeadingComment,
AliasDeclarationNode,
AllAccessorDeclarations,
AllowRequireESM,
AmbientModuleDeclaration,
and,
AnonymousType,
Expand Down Expand Up @@ -138,6 +139,7 @@ import {
Decorator,
deduplicate,
DefaultClause,
DefaultIsModuleExports,
defaultMaximumTruncationLength,
DeferredTypeReference,
DeleteExpression,
Expand Down Expand Up @@ -245,6 +247,7 @@ import {
GetAccessorDeclaration,
getAliasDeclarationFromName,
getAllJSDocTags,
getAllowRequireESM,
getAllowSyntheticDefaultImports,
getAncestor,
getAssignedExpandoInitializer,
Expand All @@ -268,6 +271,7 @@ import {
getDeclarationsOfKind,
getDeclaredExpandoInitializer,
getDecorators,
getDefaultIsModuleExports,
getDirectoryPath,
getEffectiveBaseTypeNode,
getEffectiveConstraintOfTypeParameter,
Expand Down Expand Up @@ -3634,7 +3638,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const usageMode = file && getEmitSyntaxForModuleSpecifierExpression(usage);
if (file && usageMode !== undefined) {
const targetMode = host.getImpliedNodeFormatForEmit(file);
if (usageMode === ModuleKind.ESNext && targetMode === ModuleKind.CommonJS && ModuleKind.Node16 <= moduleKind && moduleKind <= ModuleKind.NodeNext) {
const defaultIsModuleExports = getDefaultIsModuleExports(compilerOptions);
const usesNodeLikeInteropRules = DefaultIsModuleExports.Node16 <= defaultIsModuleExports && defaultIsModuleExports <= DefaultIsModuleExports.NodeNext;
if (usageMode === ModuleKind.ESNext && targetMode !== ModuleKind.ESNext && usesNodeLikeInteropRules) {
// In Node.js, CommonJS modules always have a synthetic default when imported into ESM
return true;
}
Expand All @@ -3649,6 +3655,10 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
// Declaration files (and ambient modules)
if (!file || file.isDeclarationFile) {
// Unambiguously ESM files do not have a synthetic default
if (file && host.getImpliedNodeFormatForEmit(file) === ModuleKind.ESNext) {
return false;
}
// Definitely cannot have a synthetic default if they have a syntactic default member specified
const defaultExportSymbol = resolveExportByName(moduleSymbol, InternalSymbolName.Default, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
if (defaultExportSymbol && some(defaultExportSymbol.declarations, isSyntacticDefault)) {
Expand Down Expand Up @@ -4571,7 +4581,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
const mode = contextSpecifier && isStringLiteralLike(contextSpecifier)
? host.getModeForUsageLocation(currentSourceFile, contextSpecifier)
: host.getDefaultResolutionModeForFile(currentSourceFile);
const importingFileIsJavaScript = isSourceFileJS(currentSourceFile);
const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
const allowRequireESM = getAllowRequireESM(compilerOptions);
const resolvedModule = host.getResolvedModule(currentSourceFile, moduleReference, mode)?.resolvedModule;
const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule, currentSourceFile);
const sourceFile = resolvedModule
Expand Down Expand Up @@ -4607,12 +4619,13 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, currentSourceFile, mode, resolvedModule, moduleReference);
}
if (moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext) {
const isSyncImport = (currentSourceFile.impliedNodeFormat === ModuleKind.CommonJS && !findAncestor(location, isImportCall)) || !!findAncestor(location, isImportEqualsDeclaration);
if (AllowRequireESM.Node16 <= allowRequireESM && allowRequireESM <= AllowRequireESM.NodeNext) {
const isSyncImport = (host.getImpliedNodeFormatForEmit(currentSourceFile) === ModuleKind.CommonJS && !findAncestor(location, isImportCall))
|| !!findAncestor(location, n => isImportEqualsDeclaration(n) || importingFileIsJavaScript && isVariableDeclarationInitializedToBareOrAccessedRequire(n));
const overrideHost = findAncestor(location, l => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)) as ImportTypeNode | ImportDeclaration | ExportDeclaration | undefined;
// An override clause will take effect for type-only imports and import types, and allows importing the types across formats, regardless of
// normal mode restrictions
if (isSyncImport && sourceFile.impliedNodeFormat === ModuleKind.ESNext && !hasResolutionModeOverride(overrideHost)) {
if (isSyncImport && host.getImpliedNodeFormatForEmit(sourceFile) === ModuleKind.ESNext && !hasResolutionModeOverride(overrideHost)) {
if (findAncestor(location, isImportEqualsDeclaration)) {
// ImportEquals in a ESM file resolving to another ESM file
error(errorNode, Diagnostics.Module_0_cannot_be_imported_using_this_construct_The_specifier_only_resolves_to_an_ES_module_which_cannot_be_imported_with_require_Use_an_ECMAScript_import_instead, moduleReference);
Expand Down
29 changes: 29 additions & 0 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
AllowRequireESM,
AlternateModeDiagnostics,
append,
arrayFrom,
Expand All @@ -23,6 +24,7 @@ import {
createDiagnosticForNodeInSourceFile,
createGetCanonicalFileName,
Debug,
DefaultIsModuleExports,
Diagnostic,
DiagnosticArguments,
DiagnosticMessage,
Expand Down Expand Up @@ -1196,6 +1198,33 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [
category: Diagnostics.Modules,
description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports,
},
{
name: "defaultIsModuleExports",
type: new Map(Object.entries({
auto: DefaultIsModuleExports.Auto,
node16: DefaultIsModuleExports.Node16,
nodenext: DefaultIsModuleExports.NodeNext,
})),
affectsSemanticDiagnostics: true,
affectsBuildInfo: true,
category: Diagnostics.Modules,
description: Diagnostics.Specify_the_target_runtime_s_rules_for_default_imports_targeting_CommonJS_modules,
defaultValueDescription: Diagnostics.node16_when_module_is_node16_nodenext_when_module_is_nodenext_auto_otherwise,
},
{
name: "allowRequireESM",
type: new Map(Object.entries({
never: AllowRequireESM.Never,
always: AllowRequireESM.Always,
node16: AllowRequireESM.Node16,
nodenext: AllowRequireESM.NodeNext,
})),
affectsSemanticDiagnostics: true,
affectsBuildInfo: true,
category: Diagnostics.Modules,
description: Diagnostics.Specify_the_target_runtime_s_rules_for_CommonJS_require_calls_targeting_ECMAScript_modules,
defaultValueDescription: Diagnostics.node16_when_module_is_node16_nodenext_when_module_is_nodenext_always_otherwise,
},

// Source Maps
{
Expand Down
16 changes: 16 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -6392,6 +6392,14 @@
"category": "Message",
"code": 6805
},
"Specify the target runtime's rules for default imports targeting CommonJS modules.": {
"category": "Message",
"code": 6806
},
"Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules.": {
"category": "Message",
"code": 6807
},

"one of:": {
"category": "Message",
Expand Down Expand Up @@ -6521,6 +6529,14 @@
"category": "Error",
"code": 6931
},
"'node16' when 'module' is 'node16'; 'nodenext' when 'module' is 'nodenext'; 'auto' otherwise.": {
"category": "Message",
"code": 6932
},
"'node16' when 'module' is 'node16'; 'nodenext' when 'module' is 'nodenext'; 'always' otherwise.": {
"category": "Message",
"code": 6933
},

"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
Expand Down
15 changes: 15 additions & 0 deletions src/compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7227,6 +7227,7 @@ export interface CompilerOptions {
allowJs?: boolean;
/** @internal */ allowNonTsExtensions?: boolean;
allowArbitraryExtensions?: boolean;
allowRequireESM?: AllowRequireESM;
allowSyntheticDefaultImports?: boolean;
allowUmdGlobalAccess?: boolean;
allowUnreachableCode?: boolean;
Expand Down Expand Up @@ -7254,6 +7255,7 @@ export interface CompilerOptions {
declarationMap?: boolean;
emitDeclarationOnly?: boolean;
declarationDir?: string;
defaultIsModuleExports?: DefaultIsModuleExports;
/** @internal */ diagnostics?: boolean;
/** @internal */ extendedDiagnostics?: boolean;
disableSizeLimit?: boolean;
Expand Down Expand Up @@ -7423,6 +7425,19 @@ export enum ModuleKind {
Preserve = 200,
}

export enum DefaultIsModuleExports {
Auto = 1,
Node16 = 100,
NodeNext = 199,
}

export enum AllowRequireESM {
Never = 0,
Always = 1,
Node16 = 100,
NodeNext = 199,
}

export const enum JsxEmit {
None = 0,
Preserve = 1,
Expand Down
30 changes: 30 additions & 0 deletions src/compiler/utilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
affectsDeclarationPathOptionDeclarations,
affectsEmitOptionDeclarations,
AllAccessorDeclarations,
AllowRequireESM,
AmbientModuleDeclaration,
AmpersandAmpersandEqualsToken,
AnyImportOrBareOrAccessedRequire,
Expand Down Expand Up @@ -90,6 +91,7 @@ import {
DeclarationWithTypeParameters,
Decorator,
DefaultClause,
DefaultIsModuleExports,
DestructuringAssignment,
Diagnostic,
DiagnosticArguments,
Expand Down Expand Up @@ -8852,6 +8854,30 @@ export const computedOptions = createComputedCompilerOptions({
computedOptions.module.computeValue(compilerOptions) === ModuleKind.NodeNext ? ModuleDetectionKind.Force : ModuleDetectionKind.Auto);
},
},
defaultIsModuleExports: {
dependencies: ["module", "target"],
computeValue: (compilerOptions): DefaultIsModuleExports => {
if (compilerOptions.defaultIsModuleExports !== undefined) {
return compilerOptions.defaultIsModuleExports;
}
const moduleKind = computedOptions.module.computeValue(compilerOptions);
return moduleKind === ModuleKind.Node16 ? DefaultIsModuleExports.Node16 :
moduleKind === ModuleKind.NodeNext ? DefaultIsModuleExports.NodeNext :
DefaultIsModuleExports.Auto;
},
},
allowRequireESM: {
dependencies: ["module", "target"],
computeValue: (compilerOptions): AllowRequireESM => {
if (compilerOptions.allowRequireESM !== undefined) {
return compilerOptions.allowRequireESM;
}
const moduleKind = computedOptions.module.computeValue(compilerOptions);
return moduleKind === ModuleKind.Node16 ? AllowRequireESM.Node16 :
moduleKind === ModuleKind.NodeNext ? AllowRequireESM.NodeNext :
AllowRequireESM.Always;
},
},
isolatedModules: {
dependencies: ["verbatimModuleSyntax"],
computeValue: compilerOptions => {
Expand Down Expand Up @@ -9028,6 +9054,10 @@ export const getEmitModuleResolutionKind = computedOptions.moduleResolution.comp
/** @internal */
export const getEmitModuleDetectionKind = computedOptions.moduleDetection.computeValue;
/** @internal */
export const getDefaultIsModuleExports = computedOptions.defaultIsModuleExports.computeValue;
/** @internal */
export const getAllowRequireESM = computedOptions.allowRequireESM.computeValue;
/** @internal */
export const getIsolatedModules = computedOptions.isolatedModules.computeValue;
/** @internal */
export const getESModuleInterop = computedOptions.esModuleInterop.computeValue;
Expand Down
2 changes: 2 additions & 0 deletions src/testRunner/compilerRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ class CompilerTest {
private static varyBy: readonly string[] = [
"allowArbitraryExtensions",
"allowImportingTsExtensions",
"allowRequireESM",
"allowSyntheticDefaultImports",
"alwaysStrict",
"defaultIsModuleExports",
"downlevelIteration",
"experimentalDecorators",
"emitDecoratorMetadata",
Expand Down
13 changes: 13 additions & 0 deletions tests/baselines/reference/api/typescript.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6902,6 +6902,7 @@ declare namespace ts {
allowImportingTsExtensions?: boolean;
allowJs?: boolean;
allowArbitraryExtensions?: boolean;
allowRequireESM?: AllowRequireESM;
allowSyntheticDefaultImports?: boolean;
allowUmdGlobalAccess?: boolean;
allowUnreachableCode?: boolean;
Expand All @@ -6916,6 +6917,7 @@ declare namespace ts {
declarationMap?: boolean;
emitDeclarationOnly?: boolean;
declarationDir?: string;
defaultIsModuleExports?: DefaultIsModuleExports;
disableSizeLimit?: boolean;
disableSourceOfProjectReferenceRedirect?: boolean;
disableSolutionSearching?: boolean;
Expand Down Expand Up @@ -7044,6 +7046,17 @@ declare namespace ts {
NodeNext = 199,
Preserve = 200,
}
enum DefaultIsModuleExports {
Auto = 1,
Node16 = 100,
NodeNext = 199,
}
enum AllowRequireESM {
Never = 0,
Always = 1,
Node16 = 100,
NodeNext = 199,
}
enum JsxEmit {
None = 0,
Preserve = 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "defaultIsModuleExports": "auto", /* Specify the target runtime's rules for default imports targeting CommonJS modules. */
// "allowRequireESM": "never", /* Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "defaultIsModuleExports": "auto", /* Specify the target runtime's rules for default imports targeting CommonJS modules. */
// "allowRequireESM": "never", /* Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "defaultIsModuleExports": "auto", /* Specify the target runtime's rules for default imports targeting CommonJS modules. */
// "allowRequireESM": "never", /* Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "defaultIsModuleExports": "auto", /* Specify the target runtime's rules for default imports targeting CommonJS modules. */
// "allowRequireESM": "never", /* Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "defaultIsModuleExports": "auto", /* Specify the target runtime's rules for default imports targeting CommonJS modules. */
// "allowRequireESM": "never", /* Specify the target runtime's rules for CommonJS 'require' calls targeting ECMAScript modules. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
Expand Down
Loading