Sub topic 4
Inside the src folder
This chapter assumes you have created a workspace with ng new and know basic TypeScript and HTML. It covers what the src folder contains and what each file does.
The big picture
The workspace root holds configuration. The src folder holds the code that gets built and shipped to the browser. A new workspace looks roughly like this:
src/
├── index.html
├── main.ts
├── styles.css
├── favicon.ico
└── app/
├── app.config.ts
├── app.routes.ts
├── app.component.ts
├── app.component.html
├── app.component.css
└── app.component.spec.tsNewer CLI versions name the root component files app.ts, app.html, app.css and app.spec.ts, and the class App. The roles are the same.
Files directly in src
index.htmlis the single page the browser loads. Its<body>contains the root component's selector, usually<app-root></app-root>. You do not add<script>tags here. The build tool injects the compiled bundles for you.main.tsis the entry point. It callsbootstrapApplicationto start the app. The next chapter walks through it.styles.cssholds global styles that apply to the whole application. The file extension depends on the stylesheet format you chose inng new.favicon.icois the tab icon. Static files such as images usually go in apublicfolder at the workspace root in recent versions, or insrc/assetsin older ones.
The paths src/main.ts, src/index.html and src/styles.css are not hard-coded in the CLI. They are listed in angular.json, so if you move one, you must update that file.
The app folder
The app folder holds the application itself.
| File | Purpose |
|---|---|
| `app.config.ts` | Application-wide providers, such as the router |
| `app.routes.ts` | The array of routes |
| `app.component.ts` | The root component class and its metadata |
| `app.component.html` | The root component template |
| `app.component.css` | Styles scoped to the root component |
| `app.component.spec.ts` | Unit tests for the root component |
A component is split across several files that share a name. The .ts file holds the class, the .html file holds the template, and the .css file holds styles that apply only to that component. The .spec.ts file sits next to the code it tests, so the test is easy to find.
How the pieces connect
Common errors
- Editing
index.htmlto add script tags. The build already injects them, so the scripts load twice or not at all. - Moving
main.tswithout updating thebrowseroption inangular.json. The build then fails with a file-not-found error. - Putting a global style in a component's CSS file. Component styles are scoped, so they do not reach other components. Put shared styles in
styles.css. - Forgetting that
app-rootmust match theselectorin the root component. If they differ, the page stays blank.
Exercise
You rename src/main.ts to src/start.ts, and ng build now fails. Which file do you edit, and which option do you change?
Show answer
Edit angular.json. In the build target's options, change browser from src/main.ts to src/start.ts.