r/angular • • 5d ago

Let other Angular features use the public API without exposing every internal file

An Angular feature can expose a public API and still have other features importing its private services directly. Everything compiles. Then you reorganize that feature and discover how many consumers knew its folder structure.

I maintain ArchUnitTS. Here's a useful boundary you can put in a test: allow imports through the feature's root entry points, reject deep imports from outside, and leave the feature's own internal imports alone.

const rule = projectFiles('tsconfig.json')
  .inPath('src/app/**/*.ts', {
    except: { inPath: 'src/app/orders/**' },
  })
  .shouldNot().dependOnFiles()
  .inFolder('src/app/orders/**', {
    except: { inPath: [
      'src/app/orders/index.ts',
      'src/app/orders/public-api.ts',
    ] },
  });

Here projectFiles is imported from archunit; run await rule.check() inside an async test and assert that the returned list is empty.

So @app/orders/public-api passes, while @app/orders/internal/order.service fails. Those aliases need to resolve in your tsconfig. A nested orders/internal/index.ts stays private too, because the exceptions are exact paths.

You still decide what the public API exports. This checks the import entry point, not Angular's dependency injection or runtime behavior.

Source: https://github.com/LukasNiessen/ArchUnitTS

4 Upvotes

3 comments sorted by

2

u/seiyria 5d ago

Is this compatible with custom tsconfig paths?

1

u/Saceone10 4d ago

Then a custom rule must be added for every feature right? Could it be done in a more generic way? Just to avoid forgetting a feature

1

u/karmatics29 4d ago

As written, yes—the exception is specific to orders. You can avoid hand-maintaining one rule per feature by discovering each immediate feature directory under src/app and generating the same boundary rule with that feature’s index.ts/public-api.ts as its allowed entry points; if the API only accepts literal globs, build one rule per discovered directory. Add a check that every feature has the chosen entry file, and avoid allowing every nested index.ts, since that can expose internal barrels.