Repository and File Structure
Tags: webdev, angular, programming, beginners
Published: 2023-03-14 14:49:48

_In this article, I'll show you how to create and organize a repository for your Angular application in the most optimal way._

## One Repo to rule them all
You can create your repo using different tools, and the most well-known is, of course, Angular CLI. I recommend using [Nx](https://nx.dev/angular-tutorial/1-code-generation), and I'll explain why.

No matter what tool you choose, I advise you to create a "monorepo" - a repository for multiple projects (Angular CLI also supports it out of the box).

If you will have just a single application in that repo - it is absolutely fine and will add no additional complexity or maintenance cost. But if you later will decide to create one more application in a regular (non-mono) repo - efforts for refactoring an existing non-mono repo will be huge, while in monorepo you'll do it natively. [Real-world example](https://twitter.com/FerryColum/status/1639922548539371521).

Sometimes you might have to explain this to your colleagues or managers:   
* You don't have to move your existing Angular apps into this new repo;  
* You will not move non-Angular and non-js projects to this new repo;  
* It will still be possible to build/deploy apps separately;
Every app in monorepo will have to support the same versions of dependencies, including the version of Angular;  
* Monorepo with just one app inside is a perfectly fine repo.

If you decide to go with Angular CLI, generate a workspace for multiple projects - you can find all the instructions in the Angular documentation: [link](https://angular.io/guide/file-structure#multiple-projects) (look for the "Multiple Projects" section). Also, in this case, I recommend you edit `tsconfig.json/compilerOptions/paths` to make paths pointing to the source code of libraries, not to dist folder.

## Why Nx
No worries, I'm not part of the [Nrwl Team](https://nx.app/company/) and not trying to sell their product.

I recommend using Nx monorepo for Angular apps because:

* With [nx affected](https://nx.dev/packages/nx/documents/affected), you don't need to re-build and re-test everything when you modify the code;  
* With [Nx caching](https://nx.dev/core-features/cache-task-results), many of your "test" and "build" steps will have 0s execution time - and the cache will be shared with your CI server as well;  
* [Nx Executors](https://nx.dev/plugin-features/use-task-executors) will help you with the integration of third-party tools;  
* Out-of-the-box integration with CI tools;  
* Libraries have better file structure in Nx-generated repo;  
* You'll retain access to Angular CLI generators, and will get more other generators.

The first 2 reasons will save a lot of time for you. Your development process will be much more comfortable. Your CI time will be shrunk significantly (for one of our mid-size projects, Nx reduced the average CI time from 50 minutes to 4 minutes).

Links:  
* [Generate a workspace](https://nx.dev/angular-tutorial/1-code-generation)
* [@nrwl/angular](https://nx.dev/packages/angular) package documentation

## File Structure
```
.
├── 📂 apps
│   ├── 📁 example-app-1
│   └── 📁 example-app-2 
└── 📂 libs
    ├── 📂 api
    │   └── 📂 src
    │       └── 📂 lib
    │           ├── 📂 services
    │           │   ├── 📂 users
    │           │   │   ├── 📄 interfaces.ts
    │           │   │   ├── 📄 README.md
    │           │   │   └── 📄 users.service.ts
    │           │   └── 📂 products
    │           │       ├── 📄 README.md
    │           │       └── 📄 products.service.ts
    │           ├── 📂 models
    │           │   ├── 📄 user.ts
    │           │   ├── 📄 ticket.ts
    │           │   └── 📄 index.ts
    │           └── 📄 index.ts
    ├── 📂 ui-components
    │   └── 📂 src
    │       └── 📂 lib
    │           ├── 📄 README.md
    │           └── 📂 example
    │               ├── 📄 example.component.html
    │               ├── 📄 example.component.scss
    │               ├── 📄 example.component.spec.ts 
    │               ├── 📄 example.component.ts 
    │               ├── 📄 example.component.stories.ts
    │               ├── 📄 example.store.ts
    │               └── 📄 README.md
    └── 📂 tickets
        └── 📂 src
            └── 📂 lib
                ├── 📄 README.md
                └── 📂 ticket
                    ├── 📄 ticket.component.html
                    ├── 📄 ticket.component.scss
                    ├── 📄 ticket.component.spec.ts 
                    ├── 📄 ticket.component.ts 
                    ├── 📄 ticket.store.ts
                    └── 📄 README.md
```

Here you can see:
* 2 applications (reminder: it's perfectly fine to have just one application in a monorepo);
* libs folder for libraries (in the Angular CLI workspace, libraries are located in the "projects" folder, together with applications);
* 3 libraries: `api`, `ui-components`, `tickets`;
* Library `api` has "grouping folders": services and models - there are different ways to create grouping folders for libraries, and this one is the most simple;
* `ui-components` contains components that will be shared across the entire application, maybe across multiple applications;
* `tickets` is a "feature" library - there will be components, directives, pipes, and maybe some other kind of code, that will be used only by the "tickets" part of your application;
* Some folders (like `api/models`) use the "barrel" approach and have `index.ts` file to export everything that should be public. Please use your favorite search engine to find more information about the "barrel" approach in TypeScript ;)

## Where to put things
From the structure above, you can see that most of the things are located not in `apps`, but in `libs`. Applications become, essentially, shells and loaders of the code, located in `libs` - this approach will help you increase code reuse and will encourage and help you lazy-load your "features".

So, put everything into `libs`, only put things into `apps` if they can not be moved to `libs`. 

To avoid circular dependencies, it's better to have more libraries. Also, some libraries (like `api` in our example) should be ready to be used by every other library (to read the models, at least) - it means that `api` library should not import any code from other libraries to avoid circular dependencies.

## Imports
Your `tsconfig.json` will contain `compilerOptions/paths` section, with the mapping of your libraries' names to source code paths:
```json
"paths": {
    "@wrkspc/api": ["libs/api/src/index.ts"],
    "@wrkspc/ui-components": ["libs/ui-components/src/index.ts"],
    "@wrkspc/helpers": ["libs/helpers/src/index.ts"],
    "@wrkspc/tickets": ["libs/tickets/src/index.ts"]
}
```

Here "wrkspc" is an example of your workspace name - it will be used as a grouping prefix.

_The symbol "@" can be omitted, but if you move one of your libraries to an external registry, then you will not need to modify your code (if "@prefix" will match the name of the published [scope](https://docs.npmjs.com/about-scopes))._

Because of this configuration section, Angular will understand imports like this:
```ts
import { ExampleDropdown } from '@wrkspc/ui-components';
import { User } from '@wrkspc/api';
```
Although, you can't import a library to itself, so:
```ts
// In the code, located in `libs/api`,

// You can not use this:
import { User } from '@wrkspc/api';

// it should be relative path:
import { User } from '../models';
```

Remember, that once you imported at least one file of a library, the size of the whole library will be added to the feature where you import it (if it's not an `[import type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-export)` - it will not add any size and will not affect lazy loading). 

## Advice
* Never ever add any passwords (or other "secrets" - security-wise sensitive information) to the repository. If you need some specific file to contain secrets, first add this file to .gitignore then commit it, and only after that create that file with the sensitive information;
* You might want to create file `proxy.conf.json` to avoid CORS limitations: [angular.io docs](https://angular.io/guide/build#proxying-to-a-backend-server);
* Don't underestimate the value of `README.md` files - even a couple of lines of information might save hours of searching for the person who will read this code in a few months. And the chances that that person will be you are high. That's why I recommend creating `README` for every feature and service.

---
💙 _If you enjoy my articles, consider [following me on Twitter](https://twitter.com/eugeniyoz), and/or [subscribing](https://medium.com/@eugeniyoz) to receive my new articles by email._  
🎩️ _If you or your company is looking for an Angular consultant, you can [purchase my consultations on Upwork](https://www.upwork.com/services/consultation/development-it-evgeniy-1696285343741362176?ref=project_share)._