如何避免VSCode中TypeScript自动从同层级index.ts导入
Great question! This is a common annoyance when working with barrel files (index.ts), but VSCode has built-in settings to fix this behavior without needing extra extensions (though extensions are available if you need more control).
Built-in VSCode Settings (Recommended)
You can adjust two TypeScript-specific settings to get the desired auto-import behavior:
Prefer direct file imports over directory barrels
This setting tells VSCode to look for exports directly in the source file instead of defaulting to the directory'sindex.tsbarrel. Add this to your.vscode/settings.json:"typescript.preferences.preferFileOverDirectoryImports": trueEnforce relative import specifiers
Ensure auto-imports use relative paths to the specific file (instead of non-relative or shortest paths) with this setting:"typescript.preferences.importModuleSpecifier": "relative"
For JavaScript Projects
If you're working with JavaScript instead of TypeScript, replace typescript. with javascript. in the settings above.
After applying these changes, VSCode will generate import { BAR } from './bar'; instead of import { BAR } from '.'; when auto-importing BAR in foo.ts.
Alternative: Extensions for Granular Control
If the built-in settings don't cover your edge cases, you can try extensions like Auto Import - ES6, TS, JSX, TSX (by steoates). This extension lets you configure import path patterns, including avoiding directory-based imports. However, the built-in settings should handle most standard cases.
Note
Make sure your VSCode and TypeScript version are up to date, as these settings were added in newer releases of TypeScript/VSCode.
内容的提问来源于stack exchange,提问作者user486659

