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

--moduleResolution bundler (formerly known as hybrid) #51669

Merged
merged 65 commits into from
Dec 13, 2022
Merged
Show file tree
Hide file tree
Changes from 55 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
e9f0a1a
WIP
andrewbranch Jul 28, 2022
5f9cf9d
Add extension error back unless noEmit is set
andrewbranch Jul 29, 2022
2421cf5
Add non-relative tests
andrewbranch Jul 29, 2022
660026e
Add error for importing from declaration file
andrewbranch Jul 29, 2022
2daa136
Merge branch 'main' into module-resolution/minimal
andrewbranch Sep 14, 2022
f49a368
Update unit test
andrewbranch Sep 14, 2022
af03675
Add explicit flag for importing from .ts extensions
andrewbranch Sep 14, 2022
496ef99
Add module specifier resolution changes
andrewbranch Sep 15, 2022
458c125
Add auto-import tests
andrewbranch Sep 19, 2022
7d64928
Disallow relative imports into node_modules
andrewbranch Sep 26, 2022
0249e0a
Ensure auto-imports don’t suggest ./node_modules;
andrewbranch Sep 26, 2022
6242ee3
Test a non-portable declaration emit issue
andrewbranch Sep 26, 2022
6cc0e18
Test auto-importing TSX file
andrewbranch Sep 26, 2022
240533a
Update path completions
andrewbranch Sep 26, 2022
eb9a4bb
Merge branch 'main' into module-resolution/minimal
andrewbranch Sep 26, 2022
619843e
Fix lint due to merge
andrewbranch Sep 27, 2022
2ceb4bc
Remove minimal-specific stuff
andrewbranch Oct 13, 2022
aad7fe7
Remove minimal tests
andrewbranch Oct 13, 2022
7fd3e72
Update unit tests
andrewbranch Oct 13, 2022
7cca6f3
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Oct 14, 2022
ea12012
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Oct 25, 2022
8655cf9
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 7, 2022
86dd5da
Add options
andrewbranch Oct 20, 2022
8846f31
Add customConditions option
andrewbranch Oct 21, 2022
9bc0f07
Add first tests
andrewbranch Oct 24, 2022
4545afb
CJS constructs are not allowed
andrewbranch Oct 24, 2022
e82e61d
Add another test
andrewbranch Oct 24, 2022
038783d
Fix extension adding/replacing priority
andrewbranch Oct 25, 2022
c55c454
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 8, 2022
870d807
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 8, 2022
6e1989e
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 15, 2022
a482180
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 15, 2022
89bcd01
Update test to reflect the choice not to block on unrecognized extens…
andrewbranch Nov 16, 2022
6074661
Add auto-imports and string completions tests
andrewbranch Nov 17, 2022
fa188b1
Revamp string completions ending preferences
andrewbranch Nov 18, 2022
9e03db2
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 18, 2022
c4320a2
Comment test
andrewbranch Nov 18, 2022
f04f1b5
Auto-imports of declaration files cannot use .ts extension
andrewbranch Nov 18, 2022
29039de
Have declaration file auto imports default to extensionless instead
andrewbranch Nov 18, 2022
c6b963b
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 18, 2022
e83ca2a
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 18, 2022
f98730a
Add test for custom conditions
andrewbranch Nov 18, 2022
5a01dd6
Fix indentation
andrewbranch Nov 18, 2022
4dd6d01
Add baseline showing resolvePackageJsonImports/Exports compatibility
andrewbranch Nov 18, 2022
7225671
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Nov 28, 2022
81b9e70
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Nov 28, 2022
f6fa5f3
Fix test and prevent CJS require from resolving
andrewbranch Nov 28, 2022
aeb23be
Update unit test baselines
andrewbranch Nov 28, 2022
3b1d554
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 5, 2022
e0c0375
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 5, 2022
f9414aa
Fix bad merge conflict resolution
andrewbranch Dec 5, 2022
dadc1a8
Make resolvedUsingTsExtension optional
andrewbranch Dec 5, 2022
5909643
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 5, 2022
5089aab
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 5, 2022
a88b8ad
Update missed baselines
andrewbranch Dec 6, 2022
c3575de
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 6, 2022
224bb10
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 6, 2022
b2e283c
Revert now-unnecessary API implementation changes
andrewbranch Dec 6, 2022
30afa86
Clean up
andrewbranch Dec 9, 2022
c4ba4a5
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 9, 2022
0baca5b
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 9, 2022
6e763d9
Update baselines to es5 emit
andrewbranch Dec 9, 2022
4e73a46
Merge branch 'main' into module-resolution/ts-extensions
andrewbranch Dec 13, 2022
22fbb44
Merge branch 'module-resolution/ts-extensions' into module-resolution…
andrewbranch Dec 13, 2022
d4a3b3c
Rename to `bundler`
andrewbranch Dec 13, 2022
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
3 changes: 3 additions & 0 deletions src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import {
getContainingClass,
getEffectiveContainerForJSDocTemplateTag,
getElementOrPropertyAccessName,
getEmitModuleResolutionKind,
getEmitScriptTarget,
getEnclosingBlockScopeContainer,
getErrorSpanForNode,
Expand Down Expand Up @@ -227,6 +228,7 @@ import {
ModifierFlags,
ModuleBlock,
ModuleDeclaration,
ModuleResolutionKind,
Mutable,
NamespaceExportDeclaration,
Node,
Expand Down Expand Up @@ -3583,6 +3585,7 @@ function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
if (!isBindingPattern(node.name)) {
const possibleVariableDecl = node.kind === SyntaxKind.VariableDeclaration ? node : node.parent.parent;
if (isInJSFile(node) &&
getEmitModuleResolutionKind(options) !== ModuleResolutionKind.Hybrid &&
isVariableDeclarationInitializedToBareOrAccessedRequire(possibleVariableDecl) &&
!getJSDocTypeTag(node) &&
!(getCombinedModifierFlags(node) & ModifierFlags.Export)
Expand Down
75 changes: 55 additions & 20 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ import {
ElementFlags,
EmitFlags,
EmitHint,
emitModuleKindIsNonNodeESM,
EmitResolver,
EmitTextWriter,
emptyArray,
Expand Down Expand Up @@ -309,6 +310,7 @@ import {
getResolutionModeOverrideForClause,
getResolvedExternalModuleName,
getResolvedModule,
getResolveJsonModule,
getRestParameterElementType,
getRootDeclaration,
getScriptTargetFeatures,
Expand Down Expand Up @@ -338,8 +340,8 @@ import {
hasAccessorModifier,
hasAmbientModifier,
hasContextSensitiveParameters,
HasDecorators,
hasDecorators,
HasDecorators,
hasDynamicName,
hasEffectiveModifier,
hasEffectiveModifiers,
Expand All @@ -348,8 +350,8 @@ import {
hasExtension,
HasIllegalDecorators,
HasIllegalModifiers,
HasInitializer,
hasInitializer,
HasInitializer,
hasJSDocNodes,
hasJSDocParameterTags,
hasJsonModuleEmitEnabled,
Expand Down Expand Up @@ -449,6 +451,7 @@ import {
isConstructorTypeNode,
isConstTypeReference,
isDeclaration,
isDeclarationFileName,
isDeclarationName,
isDeclarationReadonly,
isDecorator,
Expand Down Expand Up @@ -884,6 +887,7 @@ import {
setTextRangePosEnd,
setValueDeclaration,
ShorthandPropertyAssignment,
shouldAllowImportingTsExtension,
shouldPreserveConstEnums,
Signature,
SignatureDeclaration,
Expand Down Expand Up @@ -4509,6 +4513,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (
namespace.valueDeclaration &&
isInJSFile(namespace.valueDeclaration) &&
getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Hybrid &&
isVariableDeclaration(namespace.valueDeclaration) &&
namespace.valueDeclaration.initializer &&
isCommonJsRequire(namespace.valueDeclaration.initializer)
Expand Down Expand Up @@ -4693,6 +4698,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
(isModuleDeclaration(location) ? location : location.parent && isModuleDeclaration(location.parent) && location.parent.name === location ? location.parent : undefined)?.name ||
(isLiteralImportTypeNode(location) ? location : undefined)?.argument.literal;
const mode = contextSpecifier && isStringLiteralLike(contextSpecifier) ? getModeForUsageLocation(currentSourceFile, contextSpecifier) : currentSourceFile.impliedNodeFormat;
const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
const resolvedModule = getResolvedModule(currentSourceFile, moduleReference, mode);
const resolutionDiagnostic = resolvedModule && getResolutionDiagnostic(compilerOptions, resolvedModule);
const sourceFile = resolvedModule
Expand All @@ -4703,11 +4709,28 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
if (resolutionDiagnostic) {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}

if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
const importOrExport =
findAncestor(location, isImportDeclaration)?.importClause ||
findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration));
if (importOrExport && !importOrExport.isTypeOnly || findAncestor(location, isImportCall)) {
error(
errorNode,
Diagnostics.A_declaration_file_cannot_be_imported_without_import_type_Did_you_mean_to_import_an_implementation_file_0_instead,
andrewbranch marked this conversation as resolved.
Show resolved Hide resolved
getSuggestedImportSource(Debug.checkDefined(tryExtractTSExtension(moduleReference))));
}
}
else if (resolvedModule.resolvedUsingTsExtension && !shouldAllowImportingTsExtension(compilerOptions, currentSourceFile.fileName)) {
const tsExtension = Debug.checkDefined(tryExtractTSExtension(moduleReference));
error(errorNode, Diagnostics.An_import_path_can_only_end_with_a_0_extension_when_allowImportingTsExtensions_is_enabled, tsExtension);
}

if (sourceFile.symbol) {
if (resolvedModule.isExternalLibraryImport && !resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
}
if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Node16 || getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.NodeNext) {
if (moduleResolutionKind === ModuleResolutionKind.Node16 || moduleResolutionKind === ModuleResolutionKind.NodeNext) {
const isSyncImport = (currentSourceFile.impliedNodeFormat === ModuleKind.CommonJS && !findAncestor(location, isImportCall)) || !!findAncestor(location, isImportEqualsDeclaration);
const overrideClauseHost = findAncestor(location, l => isImportTypeNode(l) || isExportDeclaration(l) || isImportDeclaration(l)) as ImportTypeNode | ImportDeclaration | ExportDeclaration | undefined;
const overrideClause = overrideClauseHost && isImportTypeNode(overrideClauseHost) ? overrideClauseHost.assertions?.assertClause : overrideClauseHost?.assertClause;
Expand Down Expand Up @@ -4815,25 +4838,14 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
else {
const tsExtension = tryExtractTSExtension(moduleReference);
const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference);
const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
const resolutionIsNode16OrNext = moduleResolutionKind === ModuleResolutionKind.Node16 ||
moduleResolutionKind === ModuleResolutionKind.NodeNext;
if (tsExtension) {
const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension);
let replacedImportSource = importSourceWithoutExtension;
/**
* Direct users to import source with .js extension if outputting an ES module.
* @see https://github.com/microsoft/TypeScript/issues/42151
*/
if (moduleKind >= ModuleKind.ES2015) {
replacedImportSource += tsExtension === Extension.Mts ? ".mjs" : tsExtension === Extension.Cts ? ".cjs" : ".js";
}
error(errorNode, diag, tsExtension, replacedImportSource);
}
else if (!compilerOptions.resolveJsonModule &&
errorOnTSExtensionImport(tsExtension);
}
else if (!getResolveJsonModule(compilerOptions) &&
fileExtensionIs(moduleReference, Extension.Json) &&
getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Classic &&
moduleResolutionKind !== ModuleResolutionKind.Classic &&
hasJsonModuleEmitEnabled(compilerOptions)) {
error(errorNode, Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
}
Expand All @@ -4855,6 +4867,23 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}
}
return undefined;

function errorOnTSExtensionImport(tsExtension: string) {
const diag = Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
error(errorNode, diag, tsExtension, getSuggestedImportSource(tsExtension));
}

function getSuggestedImportSource(tsExtension: string) {
const importSourceWithoutExtension = removeExtension(moduleReference, tsExtension);
/**
* Direct users to import source with .js extension if outputting an ES module.
* @see https://github.com/microsoft/TypeScript/issues/42151
*/
if (emitModuleKindIsNonNodeESM(moduleKind) || mode === ModuleKind.ESNext) {
return importSourceWithoutExtension + (tsExtension === Extension.Mts ? ".mjs" : tsExtension === Extension.Cts ? ".cjs" : ".js");
}
return importSourceWithoutExtension;
}
}

function errorOnImplicitAnyModule(isError: boolean, errorNode: Node, { packageId, resolvedFileName }: ResolvedModuleFull, moduleReference: string): void {
Expand Down Expand Up @@ -33325,7 +33354,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
}

// In JavaScript files, calls to any identifier 'require' are treated as external module imports
if (isInJSFile(node) && isCommonJsRequire(node)) {
if (isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Hybrid && isCommonJsRequire(node)) {
return resolveExternalModuleTypeByLiteral(node.arguments![0] as StringLiteral);
}

Expand Down Expand Up @@ -42730,6 +42759,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// Import equals declaration is deprecated in es6 or above
grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
}
else if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Hybrid) {
grammarErrorOnNode(node, Diagnostics.Import_assignment_is_not_allowed_when_moduleResolution_is_set_to_hybrid_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
}
}
}
}
Expand Down Expand Up @@ -42952,6 +42984,9 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// system modules does not support export assignment
grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
}
else if (getEmitModuleResolutionKind(compilerOptions) === ModuleResolutionKind.Hybrid) {
grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_moduleResolution_is_set_to_hybrid_Consider_using_export_default_or_another_module_format_instead);
}
}
}

Expand Down Expand Up @@ -44045,7 +44080,7 @@ export function createTypeChecker(host: TypeCheckerHost): TypeChecker {
// 4). type A = import("./f/*gotToDefinitionHere*/oo")
if ((isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
((node.parent.kind === SyntaxKind.ImportDeclaration || node.parent.kind === SyntaxKind.ExportDeclaration) && (node.parent as ImportDeclaration).moduleSpecifier === node) ||
((isInJSFile(node) && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) ||
((isInJSFile(node) && getEmitModuleResolutionKind(compilerOptions) !== ModuleResolutionKind.Hybrid && isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || isImportCall(node.parent)) ||
(isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)
) {
return resolveExternalModuleName(node, node as LiteralExpression, ignoreErrors);
Expand Down
36 changes: 36 additions & 0 deletions src/compiler/commandLineParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -964,6 +964,7 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [
classic: ModuleResolutionKind.Classic,
node16: ModuleResolutionKind.Node16,
nodenext: ModuleResolutionKind.NodeNext,
hybrid: ModuleResolutionKind.Hybrid,
})),
affectsModuleResolution: true,
paramType: Diagnostics.STRATEGY,
Expand Down Expand Up @@ -1080,6 +1081,41 @@ const commandOptionsWithoutBuild: CommandLineOption[] = [
category: Diagnostics.Modules,
description: Diagnostics.List_of_file_name_suffixes_to_search_when_resolving_a_module,
},
{
name: "allowImportingTsExtensions",
type: "boolean",
affectsModuleResolution: true,
category: Diagnostics.Modules,
description: Diagnostics.Allow_imports_to_include_TypeScript_file_extensions_Requires_moduleResolution_hybrid_and_either_noEmit_or_emitDeclarationOnly_to_be_set,
defaultValueDescription: false,
},
{
name: "resolvePackageJsonExports",
type: "boolean",
affectsModuleResolution: true,
category: Diagnostics.Modules,
description: Diagnostics.Use_the_package_json_exports_field_when_resolving_package_imports,
defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_hybrid_otherwise_false,
},
{
name: "resolvePackageJsonImports",
type: "boolean",
affectsModuleResolution: true,
category: Diagnostics.Modules,
description: Diagnostics.Use_the_package_json_imports_field_when_resolving_imports,
defaultValueDescription: Diagnostics.true_when_moduleResolution_is_node16_nodenext_or_hybrid_otherwise_false,
},
{
name: "customConditions",
type: "list",
element: {
name: "condition",
type: "string",
},
affectsModuleResolution: true,
category: Diagnostics.Modules,
description: Diagnostics.Conditions_to_set_in_addition_to_the_resolver_specific_defaults_when_resolving_imports,
},

// Source Maps
{
Expand Down
48 changes: 44 additions & 4 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -3563,6 +3563,10 @@
"category": "Error",
"code": 2845
},
"A declaration file cannot be imported without 'import type'. Did you mean to import an implementation file '{0}' instead?": {
"category": "Error",
"code": 2846
},

"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
Expand Down Expand Up @@ -4221,6 +4225,26 @@
"category": "Error",
"code": 5095
},
"Option 'allowImportingTsExtensions' can only be used when 'moduleResolution' is set to 'hybrid' and either 'noEmit' or 'emitDeclarationOnly' is set.": {
"category": "Error",
"code": 5096
},
"An import path can only end with a '{0}' extension when 'allowImportingTsExtensions' is enabled.": {
"category": "Error",
"code": 5097
},
"Option '{0}' can only be used when 'moduleResolution' is set to 'node16', 'nodenext', or 'hybrid'.": {
"category": "Error",
"code": 5098
},
"Import assignment is not allowed when 'moduleResolution' is set to 'hybrid'. Consider using 'import * as ns from \"mod\"', 'import {a} from \"mod\"', 'import d from \"mod\"', or another module format instead.": {
"category": "Error",
"code": 5099
},
"Export assignment cannot be used when 'moduleResolution' is set to 'hybrid'. Consider using 'export default' or another module format instead.": {
"category": "Error",
"code": 5100
},

"Generates a sourcemap for each corresponding '.d.ts' file.": {
"category": "Message",
Expand Down Expand Up @@ -4443,10 +4467,6 @@
"category": "Message",
"code": 6066
},
"Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6).": {
"category": "Message",
"code": 6069
},
"Initializes a TypeScript project and creates a tsconfig.json file.": {
"category": "Message",
"code": 6070
Expand Down Expand Up @@ -5430,6 +5450,26 @@
"category": "Message",
"code": 6406
},
"Allow imports to include TypeScript file extensions. Requires '--moduleResolution hybrid' and either '--noEmit' or '--emitDeclarationOnly' to be set.": {
"category": "Message",
"code": 6407
},
"Use the package.json 'exports' field when resolving package imports.": {
"category": "Message",
"code": 6408
},
"Use the package.json 'imports' field when resolving imports.": {
"category": "Message",
"code": 6409
},
"Conditions to set in addition to the resolver-specific defaults when resolving imports.": {
"category": "Message",
"code": 6410
},
"`true` when 'moduleResolution' is 'node16', 'nodenext', or 'hybrid'; otherwise `false`.": {
"category": "Message",
"code": 6411
},

"The expected type comes from property '{0}' which is declared here on type '{1}'": {
"category": "Message",
Expand Down
Loading