【问题标题】:baseUrl in tsconfig.app.json is not overiding the baseUrl in tsconfig.jsontsconfig.app.json 中的 baseUrl 没有覆盖 tsconfig.json 中的 baseUrl
【发布时间】:2019-05-13 20:27:19
【问题描述】:

在 Angular 6 中,我使用 ng generate application,因为我将拥有多个必须共享一些库的应用程序。使用这种方法,我的文件夹结构如下:

项目->app1->tsconfig.app.json

项目->app2->tsconfig.app.json

并且 tsconfig.jsonprojects 文件夹处于同一级别

注意:当我们在 Angular 6 中使用 ng g application 时,会创建这样的文件夹结构。

我想在我的组件或服务等中使用相对路径来进行这样的导入:

从 'src/services/example.service' 导入 { ExampleService };

而不必像这样使用它:

从'../../../services/example.service'导入{ ExampleService};

如何为上述创建的单个应用程序提供此功能?

我的 tsconfig.json 是这样的

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "downlevelIteration": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

而我的 tsconfig.app.json 是这样的:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/app",
    "types": ["node"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

我曾尝试在 tsconfig.app.json 中这样给予:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "../../out-tsc/app",
    "types": ["node"]
  },
  "exclude": ["test.ts", "**/*.spec.ts"]
}

但这没有用。

我想使用相对路径直接使用src来消除多级分辨率(../../../)

【问题讨论】:

    标签: angular angular6 angular7 typescript2.0


    【解决方案1】:

    您应该看看tsconfig.json 中的paths compilerOption。例如,有了它,您可以这样做:

    "compilerOptions": {
      "paths": {
        "@services/*": [
          "src/services/*"
        ]
      }
    } 
    

    然后您可以使用此路径从 typescript 项目中的任何文件导入:

    import { ExampleService } from '@services/example.service';
    

    不用@,随便起名字就可以了

    【讨论】:

    • 但是tsconfig.app.json里面的baseUrl是不是不能用?
    • @sand 也许,但你遇到的问题有设置路径的解决方案,而不是通过干预 baseUrl :)
    • 是的。由于我正在尝试重组已经存在的应用程序,因此我希望仅更新 baseUrl 就可以解决问题:) 谢谢
    猜你喜欢
    • 2018-09-26
    • 2018-03-23
    • 1970-01-01
    • 2018-10-27
    • 2018-07-20
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多