首页 文章

typescript无法解析导入中的非相对路径

提问于
浏览
3

我有这样的项目结构

|--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'

打字稿文档说下:

对于moduleB的非相对导入,例如来自“moduleB”的import ,在源文件/root/src/folder/A.ts中,将导致尝试以下位置来定位“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

提前致谢 . 附:在我的webpack.config中,我已经将root.resolve设置为src,并且所有bundle都正确 . Typescript-loader将错误打印到终端,但所有内容都捆绑在一起并正常工作

1 回答

  • 1

    所以我可以猜到它的“为什么”部分,但我对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'
    

相关问题