Skip to content

--moduleResolution minimal #50153

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

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Ensure auto-imports don’t suggest ./node_modules;
  • Loading branch information
andrewbranch committed Sep 26, 2022
commit 0249e0a93e08a4365764a0ff92b2b0dfd0daacc0
23 changes: 19 additions & 4 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3598,6 +3598,7 @@ namespace ts {
(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 @@ -3609,7 +3610,22 @@ namespace ts {
error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
}

if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
if (moduleResolutionKind === ModuleResolutionKind.Minimal && pathContainsNodeModules(moduleReference)) {
// A relative import into node_modules is a problem for a few reasons:
// 1. Portability - if the code gets published as a library, it will very likely break
// 2. It's unclear how we should resolve types. By typical relative import rules, we
// would ignore package.json fields that tell us where to find types and would have
// no special behavior linking up node_modules/@types with their implementations -
// we would only find .d.ts files as siblings of .js files. Any package that puts
// their types in a separate directory, or is typed by @types, would be broken.
// Some of these redirections would be safe to do, but others might reflect
// Node-specific resolution features that would only work with non-relative imports.
// The module resolver still returns a result, because it's possible for a module in
// node_modules to end up in the program, and module specifier generation assumes that it
// is always possible to generate a module specifier, even if it also generates a diagnostic.
error(errorNode, Diagnostics.Relative_imports_into_node_modules_are_not_allowed);
}
else if (resolvedModule.resolvedUsingTsExtension && isDeclarationFileName(moduleReference)) {
const importOrExport =
findAncestor(location, isImportDeclaration)?.importClause ||
findAncestor(location, or(isImportEqualsDeclaration, isExportDeclaration)) as ImportEqualsDeclaration | ExportDeclaration | undefined;
Expand All @@ -3629,7 +3645,7 @@ namespace ts {
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 @@ -3737,7 +3753,6 @@ namespace ts {
else {
const tsExtension = tryExtractTSExtension(moduleReference);
const isExtensionlessRelativePathImport = pathIsRelative(moduleReference) && !hasExtension(moduleReference);
const moduleResolutionKind = getEmitModuleResolutionKind(compilerOptions);
const resolutionIsNode16OrNext = moduleResolutionKind === ModuleResolutionKind.Node16 ||
moduleResolutionKind === ModuleResolutionKind.NodeNext;
if (moduleResolutionKind === ModuleResolutionKind.Minimal && pathContainsNodeModules(moduleReference)) {
Expand All @@ -3748,7 +3763,7 @@ namespace ts {
}
else if (!compilerOptions.resolveJsonModule &&
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 Down
13 changes: 0 additions & 13 deletions src/compiler/moduleNameResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2705,19 +2705,6 @@ namespace ts {
if (resolvedUsingSettings) {
return resolvedUsingSettings;
}
if (isExternalModuleNameRelative(moduleName) && pathContainsNodeModules(moduleName)) {
// A relative import into node_modules is a problem for a few reasons:
// 1. Portability - if the code gets published as a library, it will very likely break
// 2. It's unclear how we should resolve types. By typical relative import rules, we
// would ignore package.json fields that tell us where to find types and would have
// no special behavior linking up node_modules/@types with their implementations -
// we would only find .d.ts files as siblings of .js files. Any package that puts
// their types in a separate directory, or is typed by @types, would be broken.
// Some of these redirections would be safe to do, but others might reflect
// Node-specific resolution features that would only work with non-relative imports.
// There's a diagnostic issued for this case in the checker.
return noPackageId(/*resolved*/ undefined);
}
const resolvedRelative = loadModuleFromFileNoImplicitExtensions(extensions, candidate, /*onlyRecordFailures*/ false, state);
if (resolvedRelative) {
return noPackageId(resolvedRelative);
Expand Down
3 changes: 2 additions & 1 deletion src/services/codefixes/importFixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -662,7 +662,8 @@ namespace ts.codefix {
const compilerOptions = program.getCompilerOptions();
const moduleSpecifierResolutionHost = createModuleSpecifierResolutionHost(program, host);
const getChecker = createGetChecker(program, host);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(getEmitModuleResolutionKind(compilerOptions));
const moduleResolution = getEmitModuleResolutionKind(compilerOptions);
const rejectNodeModulesRelativePaths = moduleResolutionUsesNodeModules(moduleResolution) || moduleResolution === ModuleResolutionKind.Minimal;
const getModuleSpecifiers = fromCacheOnly
? (moduleSymbol: Symbol) => ({ moduleSpecifiers: moduleSpecifiers.tryGetModuleSpecifiersFromCache(moduleSymbol, sourceFile, moduleSpecifierResolutionHost, preferences), computedWithoutCache: false })
: (moduleSymbol: Symbol, checker: TypeChecker) => moduleSpecifiers.getModuleSpecifiersWithCacheInfo(moduleSymbol, checker, compilerOptions, sourceFile, moduleSpecifierResolutionHost, preferences);
Expand Down
11 changes: 8 additions & 3 deletions src/services/completions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ namespace ts.Completions {

const enum GlobalsSearch { Continue, Success, Fail }

interface ModuleSpecifierResolutioContext {
interface ModuleSpecifierResolutionContext {
tryResolve: (exportInfo: readonly SymbolExportInfo[], symbolName: string, isFromAmbientModule: boolean) => ModuleSpecifierResolutionResult;
resolvedAny: () => boolean;
skippedAny: () => boolean;
Expand All @@ -190,15 +190,20 @@ namespace ts.Completions {
preferences: UserPreferences,
isForImportStatementCompletion: boolean,
isValidTypeOnlyUseSite: boolean,
cb: (context: ModuleSpecifierResolutioContext) => TReturn,
cb: (context: ModuleSpecifierResolutionContext) => TReturn,
): TReturn {
const start = timestamp();
const moduleResolution = getEmitModuleResolutionKind(program.getCompilerOptions());
// Under `--moduleResolution nodenext`, we have to resolve module specifiers up front, because
// package.json exports can mean we *can't* resolve a module specifier (that doesn't include a
// relative path into node_modules), and we want to filter those completions out entirely.
// Under `--moduleResolution minimal`, we want to reject relative module specifiers into
// node_modules, so need to exhaust any other possibilities for how those can be referenced.
// Import statement completions always need specifier resolution because the module specifier is
// part of their `insertText`, not the `codeActions` creating edits away from the cursor.
const needsFullResolution = isForImportStatementCompletion || moduleResolutionRespectsExports(getEmitModuleResolutionKind(program.getCompilerOptions()));
const needsFullResolution = isForImportStatementCompletion
|| moduleResolutionRespectsExports(moduleResolution)
|| moduleResolution === ModuleResolutionKind.Minimal;
let skippedAny = false;
let ambientCount = 0;
let resolvedCount = 0;
Expand Down
15 changes: 15 additions & 0 deletions tests/baselines/reference/autoImportsMinimal1.baseline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
```ts
// @Filename: /main.ts
/*|*/
```

## From completions

- `fromLocal` from `"./local.js"`

```ts
import { fromLocal } from "./local.js";

fromLocal
```

15 changes: 15 additions & 0 deletions tests/baselines/reference/autoImportsMinimal2.baseline.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
```ts
// @Filename: /main.ts
/*|*/
```

## From completions

- `fromLocal` from `"./local.ts"`

```ts
import { fromLocal } from "./local.ts";

fromLocal
```

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy