You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免VSCode中TypeScript自动从同层级index.ts导入

How to Force VSCode to Use Specific File Paths for Auto-Imports Instead of "."

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).

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's index.ts barrel. Add this to your .vscode/settings.json:

    "typescript.preferences.preferFileOverDirectoryImports": true
    
  • Enforce 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 13:13:13