在我们的 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 试图了解到底是什么问题并尝试不同的故障排除选项后,我开始了解 baseUrl 和 Path 如何协同工作
注意:此解决方案适用于 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/