Search code examples
angulartypescriptpathangular-module

TypeScript custom paths do not work without barreling


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...


Solution

  • 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'