簡體   English   中英

typescript無法解析導入中的非相對路徑

[英]typescript can't resolve non-relative path in import

我有這樣的項目結構

|--src
     |--app.component
                    |--index.ts
     |--home.component
                    |--index.ts
|--tsconfig.json
|--webpack.config.js

我正在嘗試在app.component-index.ts中執行以下操作

import { HomeComponent } from 'components/home.component'

打字稿無法找到此模塊並拋出

error TS2307: Cannot find module 'home.component'

打字稿文檔說下:

在源文件/root/src/folder/A.ts中對moduleB進行非相對導入(例如從“moduleB”導入{b})將導致嘗試以下位置來定位“moduleB”:

/root/src/folder/moduleB.ts
/root/src/moduleB.ts
/root/moduleB.ts
/moduleB.ts 

所以對於我的情況,我希望它會是這樣的

/src/components/app.component/components/home.component
/src/components/components/home.component
/src/components/home.component

提前致謝。 PS在我的webpack.config中我已經將root.resolve設置為src並且所有bundle都正確。 Typescript-loader將錯誤打印到終端,但所有內容都捆綁在一起並正常工作

所以我可以猜到它的“為什么”部分,但我對TypeScript相對較新。 我已經得到了這個工作,所以我會盡力解釋基於該解決方案。

如果符合以下條件,您對TypeScript文檔的期望大多是正確的:

'components/home.component'

被視為“非相對進口”。 我非常肯定(基於對我有用的解決方案)TypeScript將其視為來自tsconfig.json中'compilerOptions.baseUrl'字段的絕對路徑。

對我有用的是設置它:

{
  "compilerOptions": {
    "baseUrl": ".",

    // Other options
  }
}

這本質上告訴TypeScript嘗試找到類似的東西

'components/home.component'

通過在tsconfig.json文件的同一目錄中查找名為“components”的目錄,然后在其中查找名為“home.component”的文件/目錄。

所以,如果您的結構如下:

|--src
   |--app.component
       |--index.ts
   |--home.component
       |--index.ts
|--tsconfig.json
|--webpack.config.js

並將baseUrl設置為“。” 你可能需要格式化你的導入

import { HomeComponent } from 'src/home.component'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM