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

lgi*_*lap 7 path typescript tsconfig angular

在我们的angular2项目中,我们将所有模型的ts文件放在特定的文件夹中:/ app/common/model/*.我可以用亲戚路径在我的组件中调用它们,但它非常费力.所以2个解决方案,最好的是自定义路径:StackOverflow:SystemJS和ES模块导入的相对路径.但我的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/*"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在我的组件中: import { Address } from 'mymodel/address.model';

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

第二种解决方案:Stackoverflow:Angular 2,在不同文件夹之间导入

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

和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/*"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我们对所有型号的页面加载都有404.也许是systemjs文件中的配置?

在这两种情况下,我认为"outdir"参数是问题,我们错过了一些东西.

非常感谢您的帮助!

问候,

TypeScript:2.0.6 Angular:2.0.0

Vir*_*raj 2

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

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

如果您使用baseUrl:“。” 如下所示,它在 VScode 中有效,但在编译时无效

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["src/app/*"]
    }    
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "paths": {
      "@myproject/*": ["app/*"],
      "testing/*": ["testing/*"]
    }    
}
Run Code Online (Sandbox Code Playgroud)

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

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