打字稿不能解决导入中的非相对路径

时间:2016-04-27 20:39:52

标签: import typescript webpack

我有像这样的项目结构

+ (UIView *)viewWithCondition:(BOOL (^)(UIView *view))condition inView:(UIView *)view
{
    // non-recursive BFS traversal of a view hierarchy until specified UIView matching condition is found

    NSMutableArray<UIView *> *stack = [[NSMutableArray alloc] initWithObjects:view, nil];
    UIView *curr;

    while ([stack count] > 0)
    {
        curr = [stack firstObject];
        [stack removeObject:curr];

        if (condition((UIView *)curr))
        {
            return (UIView *)curr;
        }

        [stack addObjectsFromArray:[curr subviews]];
    }

    return nil;
}

我正在尝试在app.component-index.ts

中执行以下操作
|--src
     |--app.component
                    |--index.ts
     |--home.component
                    |--index.ts
|--tsconfig.json
|--webpack.config.js

打字稿无法找到此模块并抛出

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

打字稿文档说下:

  

对moduleB的非相对导入,例如来自&#34; moduleB&#34;的import {b},   在源文件/root/src/folder/A.ts中,将导致尝试   以下位置用于定位&#34; moduleB&#34;:

error TS2307: Cannot find module 'home.component'

所以对于我的情况,我希望它会像

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

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

1 个答案:

答案 0 :(得分:1)

所以我可以猜到&#34;为什么&#34;部分内容,但我对TypeScript来说相对较新。我已经让这个工作了,所以我会尝试尽可能地根据解决方案进行解释。

如果符合以下条件,您对TypeScript文档的期望大多是正确的:

'components/home.component'

被视为“非相对进口”。我非常肯定(基于对我有用的解决方案)TypeScript将其视为来自&#39; compilerOptions.baseUrl&#39;的绝对路径。 tsconfig.json中的字段。

对我有用的是设置它:

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

    // Other options
  }
}

这基本上告诉TypeScript尝试找到像

这样的东西
'components/home.component'

通过在tsconfig.json文件的同一目录中查找名为&#39; components&#39;的目录。然后在其中查找名为&#39; home.component&#39;。

的文件/目录

因此,如果您的结构如下:

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

您将baseUrl设置为&#34;。&#34;您可能需要格式化导入,如

import { HomeComponent } from 'src/home.component'
相关问题