2

In Angular 6, I'm using ng generate application as I will have more than one application which has to share some libraries. With this approach, I have folder structure like this:

projects->app1->tsconfig.app.json

projects->app2->tsconfig.app.json

And the tsconfig.json is in the same level as projects folder

Note: Folder structure like this will be created when we use ng g application in Angular 6.

I want to use relative paths in my components or services etc for imports like this:

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

instead of having to use it something like this:

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

How can I provide this features for the individual applications that are created like mentioned above?

My tsconfig.json is like this

{
  "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"
    ]
  }
}

And my tsconfig.app.json is like this:

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

I have tried giving like this in the tsconfig.app.json:

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

But that didn't work.

I want to use the relative paths by using src directly to eliminate the multiple level resolution (../../../)

sand
  • 33
  • 1
  • 6

1 Answers1

2

You should have a look at the paths compilerOption from tsconfig.json. With it you can do this for instance:

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

You can then import from any file inside your typescript project using this path:

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

No need to use @, you can name it whatever you like

Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • But is it not possible to use the baseUrl inside tsconfig.app.json? – sand May 14 '19 at 04:21
  • @sand maybe, but the issue you are having has the solution of setting a path, not by medling with the baseUrl :) – Poul Kruijt May 14 '19 at 07:34
  • Yes. Since I am trying to restructure an already present application, I was hoping that just updating the baseUrl would do the trick :) Thanks though – sand May 14 '19 at 08:21