Angular2 导入绝对路径或自定义路径(typescript 2)

标签 angular typescript path tsconfig

在我们的 angular2 项目中,我们将所有模型的 ts 文件放在一个特定的文件夹中:/app/common/model/*。 我可以在我的组件中用亲戚路径调用它们,但这非常费力。 所以 2 个解决方案,最好是自定义路径:StackOverflow: Relative Paths for SystemJS & ES module imports . 但是我的IDE找不到路径。这是我的 tsconfig :

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "mymodel/*": [
        "app/common/model/*"
      ]
    }
  }
}

在我的组件中: 从 'mymodel/address.model' 导入 { Address };

IDE: [ts] 找不到模块.... 我尝试在路径中使用或不使用 *

第二种解决方案:Stackoverflow: Angular 2, imports between different folders

IDE 和编译都可以,组件中有完整路径: 从 'common/model/address.model' 导入 { Address };

和 tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "*": [
        "app/*",
        "node_modules/*"
      ]
    }
  }
}

但是我们在所有模型的页面加载时都有 404。 也许是 systemjs 文件中的配置?

在这两种情况下,我认为“outdir”参数是问题所在,我们遗漏了一些东西。

非常感谢您的帮助!

问候,

typescript :2.0.6 Angular :2.0.0

最佳答案

在互联网上努力搜索 n 试图了解到底是什么问题并尝试不同的故障排除选项后,我开始了解 baseUrlPath 如何协同工作

注意:此解决方案适用于 Angular Cli 1.x。不确定其他工具,

如果你像下面那样使用 baseUrl:"." 它在 VScode 中有效但在编译时无效

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["src/app/*"]
    }    
}

就我的理解和我的工作应用程序并检查了 angular aio 代码,我建议使用 baseUrl:""src 如下所示

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "paths": {
      "@myproject/*": ["app/*"],
      "testing/*": ["testing/*"]
    }    
}

通过将基本 URL 作为源(src 目录),编译器可以正确解析模块。

我希望这有助于人们解决此类问题。

关于Angular2 导入绝对路径或自定义路径(typescript 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40345179/

相关文章:

javascript - ionic 模态的 Angular 传递输入

java - ZipOutputStream 相对路径

c# - WPF C# 路径 : How to get from a string with Path Data to Geometry in Code (not in XAML)

angular - 火力基地/火力商店 : create and store unique id for documents (users for USERID)

angularjs - Angular-ui-bootstrap 模式和 typescript

angular - 名称为 : 'eventGraphicAttachment' 的表单控件没有值访问器

typescript - 在 Visual Studio Code 中使用 TypeScript 时,如何将 TS 警告配置为显示为错误?

java - Make 找不到 tools.jar

angular - NPM - 无法从 lodash 库中找到名称 'Many' 和命名空间 '_'

angular - 是否可以在 Angular 2中读取其他应用程序的本地存储?