1

I would like to have in shared module class that I can import in other modules. Something like this:

import { SomeClass } from '/path/to/shared/module'

I want to avoid directly importing class like

import { SomeClass } from '/path/to/class'

Basically I want something like importing from packages in Java or from namespace in c#. I can find only using components, services or directives, from shared modules but no classes. I know I can use barrel files but this seems like better solution for my needs

Ivan ho ho ho
  • 57
  • 3
  • 9
  • Does this answer your question? [How to create a shared module](https://stackoverflow.com/questions/47398896/how-to-create-a-shared-module) – OAH May 04 '20 at 02:27

2 Answers2

3

Use path aliases

folder structure:

src
└── shared
    ├── module1
    │   ├── index.ts
    │   └── module1.module.ts
    └── module2
        ├── index.ts
        └── module2.module.ts

src/shared/module1/index.ts

export * from './module1.module.ts'

src/shared/module2/index.ts

export * from './module2.module.ts'

add alias in tsconfig.json:

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

and that's how you use it:

import { Module1 } from '@shared/module1';
Chris
  • 2,117
  • 13
  • 18
1

It's the same pattern as doing it with a component, service, directive, etc...

Figure out a good home for any shared classes throughout your application.

Your shared class:

export class SomeClass {
    ...
}

Any place you want to use your share class:

import { SomeClass } './path/to/shared/class';

Take a look at some of the examples on MDN:

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import

However, if you're trying to make this super "angularized", you may want to look at using a library

mwilson
  • 12,295
  • 7
  • 55
  • 95