網站搜尋

正則表達式 - 將 TypeScript 中的相對匯入轉換為絕對匯入


在 .tsconfig 中將 baseUrl 屬性設置為 src,使我可以像這樣相對於 baseUrl 導入模組:

import { ArrowRightIcon } from 'Shared/icons/navigation'

而不是:

import { ArrowRightIcon } from '../../../Shared/icons/navigation'

問題

由於任何 IDE 的 查找全部 功能無法理解上下文,我該如何高效地將應用程式中數千個此類相對導入轉換為絕對導入?

目前,我必須將所有出現的 ../../../Shared/、../../../../Shared/ 等等,替換為 Shared/,並且針對 src 中的所有目錄進行操作。即使我使用 regex 幫助進行替換,在以下示例中第 2 種情況仍然無濟於事。

其他例子:

  1. import { getActiveTabIdx } from 'Shared/utils/shared.helpers'

取代 import { getActiveTabIdx } from '../../../../../../../Shared/utils/shared.helpers'

  1. import { TabWithLink } from 'Shared/components/Header'

而不是 import { TabWithLink } from '../../components/Header'

  1. import { layoutReducer } from 'Layout/state/layout.reducer'

取代 import { layoutReducer } from '../../Layout/state/layout.reducer'

我的目錄結構是:

.
├── src
│   ├── Shared
│   │  ├── components
│   │  ...
│   ├── Notification
│   │  ├── components
│   │  ...
│   ├── Planning
│   │  ├── components
│   │  ...
│   ├── Behaviour
│   │  ├── components
│   │  ...
│   └── Layout
│   │  ├── components
│   │  ├── state
│   ...
...

目前安裝的版本:

  • TypeScript: 4.2.4
  • vscode: 1.57.1