1
votes

I've spent all morning on ts-paths to shorten my import paths.

I can confirm that custom paths work IF you setup barreling (an index file exports your modules)

root
├── client
│   ├──tsconfig.json
│   ├── src
│       ├──app
│           ├── shared
│               ├── services
│                   ├── some.service.ts
├── common
│   ├── index.ts // exports * from each file

My NG8 tsconfig.ts file:

"compilerOptions": {
    "baseUrl": ".",
    "paths": {
        "@common": ["../common"], // works with barreling
        "@services": ["./src/app/shared/services"] // only works with barreling
    },

@services does not work... unless I setup barreling
(adding an index.ts file in shared folder with export * from './some.service';)

@common works out of the box because of barreling like above.

Am I missing something or is everything I've read leaving out a requirement to export your modules in this way?

My research:
https://angularfirebase.com/lessons/shorten-typescript-imports-in-an-angular-project/
https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping
How to use paths in tsconfig.json?
many more...

1
This should work, try without the leading ./ Just "src/app/shared/services". Though I think there should be a tsconfig.json in the root - C_Ogoo
Hey @C_Ogoo so the paths are all correct because it works when an index.ts file exists with service classes exported... Also I've been trying all day with every path variation I can think. Making the path src/app/shared/services breaks it... Unless the index with exports exist in which case it still works. - Ben Racicot
Ahh i misread / misunderstood .. in the services directory. you dont have a barrel file, but individual fies like .../services/some-file.ts - C_Ogoo
Yes, I've updated the structure for clarity. There are many service files in that folder. - Ben Racicot

1 Answers

2
votes

With the set-up you have (without a barrel index.ts file) your paths need to be slightly different.

"paths": {
  "@services/*": ["src/app/shared/services/*"],
},

You will then be able to import using:

import { SomeService } from '@services/some.service'