- For navigating/exploring the workspace, invoke the
nx-workspaceskill first - it has patterns for querying projects, targets, and dependencies - When running tasks (for example build, lint, test, e2e, etc.), always prefer running the task through
nx(i.e.nx run,nx run-many,nx affected) instead of using the underlying tooling directly - Prefix nx commands with the workspace's package manager (e.g.,
pnpm nx build,npm exec nx test) - avoids using globally installed CLI - You have access to the Nx MCP server and its tools, use them to help the user
- For Nx plugin best practices, check
node_modules/@nx/<plugin>/PLUGIN.md. Not all plugins have this file - proceed without it if unavailable. - NEVER guess CLI flags - always check nx_docs or
--helpfirst when unsure
- For scaffolding tasks (creating apps, libs, project structure, setup), ALWAYS invoke the
nx-generateskill FIRST before exploring or calling MCP tools
- USE for: advanced config options, unfamiliar flags, migration guides, plugin configuration, edge cases
- DON'T USE for: basic generator syntax (
nx g @nx/react:app), standard commands, things you already know - The
nx-generateskill handles generator discovery internally - don't call nx_docs just to look up generator syntax
You are an expert in TypeScript, Angular, and scalable web application development. You write functional, maintainable, performant, and accessible code following Angular and TypeScript best practices.
Important
The conventions below are mandatory. Every code change, generation, or refactoring must follow them. When in doubt, look at an existing file in the codebase for reference rather than guessing.
- All imports at the top. Never use
import('module').Somethinginline in functions, methods, or class bodies. The sole exception is theDepsservice (shared/deps.ts), which lazy-loads heavy third-party libraries (e.g.,luxon,three,uuid) via dynamicimport(). - Type-only imports. When importing only types, always use
import typeorimport { type Foo }:import type { DateTime } from 'luxon'; import type * as THREE from 'three';
- Import grouping. Separate imports into groups with blank lines in the following order enforced by ESLint
import-x/order:- Angular / third-party packages (
@angular/*,rxjs, etc.) - Project-internal relative imports (e.g.,
../../shared/deps) - Local relative imports (e.g.,
./background/background)
- Angular / third-party packages (
- No barrel re-exports. Import directly from the source file, never through an
index.tsbarrel.
- Use strict type checking; avoid
any—useunknownwhen the type is uncertain. - Prefer type inference when the type is obvious from the right-hand side.
- Use
type(notinterface) for type definitions. ESLint enforces@typescript-eslint/consistent-type-definitions: ['error', 'type']. - Prefix unused variables/parameters with
_(e.g.,_event).
- All filenames must be kebab-case (enforced by ESLint
unicorn/filename-case). - Component/service files use the bare name without a suffix. Examples:
home.ts,settings.ts,deps.ts. - Test files use
.spec.ts:home.spec.ts,deps.spec.ts. - Supporting file types follow the
name.type.tspattern:app.routes.ts,app.config.ts,app.routes.server.ts,app.config.server.ts.
- Always standalone. Do NOT set
standalone: truein the decorator; it is the default in Angular v20+. - Always use external templates and styles. Use
templateUrlandstyleUrl(singular), never inlinetemplate/styles. - Use paths relative to the component TS file:
templateUrl: './home.html',styleUrl: './home.css'. - File names match the component directory name:
home/home.ts,home/home.html,home/home.css. - No
changeDetectionproperty required unless explicitly needed; OnPush is default in v20+.
- Component classes are PascalCase nouns without any suffix:
Home,Navbar,Background,ThemeSwitcher,PageNavigationLoader. - Never use
Componentsuffix (e.g.,).HomeComponent
- Components use
app-prefix:selector: 'app-home',selector: 'app-navbar'.
- Use the
hostproperty in the@Componentdecorator, never@HostBindingor@HostListener:@Component({ host: { class: /* tw */ 'block min-h-full w-full', }, })
- Add the
/* tw */annotation before Tailwind class strings in thehostproperty to enable IDE IntelliSense.
- Use the
input()andoutput()signal functions, never@Input()or@Output()decorators.
- Use self-closing tags for components without projected content:
<app-navbar />,<router-outlet />.
- Use
signal()for local/mutable state. - Use
computed()for derived state. - Use
toSignal()to convert Observables into signals. - Never use
mutateon signals; useupdateorset.
Caution
Effects must be declared as readonly class properties, never inside the constructor.
// ✅ CORRECT — effect assigned to a class property
export class Settings {
readonly toggleThemeClassEffect = effect(() => {
if (this.isDarkTheme()) {
this.document.documentElement.classList.add('dark');
} else {
this.document.documentElement.classList.remove('dark');
}
});
}
// ❌ WRONG — effect created inside the constructor
export class Settings {
constructor() {
effect(() => {
/* ... */
}); // DO NOT DO THIS
}
}This convention applies to all uses of effect() in both services and components. Name effects descriptively: setDeviceIdEffect, toggleThemeClassEffect, initEffect.
- Use
httpResource(from@angular/common/http) for declarative data fetching in components. - Assign to a
readonlyclass property, just like signals:readonly vertexShader = httpResource.text(() => VERTEX_SHADER_URL);
- Use
inject()function for DI, never constructor parameter injection. - Mark injected dependencies as
private readonly:private readonly settings = inject(Settings);
- Services are PascalCase nouns without any suffix:
Deps,Settings,UI,SEO. - Never use
Servicesuffix (e.g.,).SettingsService
- Use
providedIn: 'root'for singleton services. - Register app-level services (e.g.,
Deps,Settings,UI,SEO) in the rootapp.config.tsprovidersarray.
-
Components should alias service signals as readonly class properties:
export class PageNavigationLoader { private readonly ui = inject(UI); readonly loading = this.ui.loading.asReadonly(); readonly navigating = this.ui.navigating; }
import()for external/heavy libraries is only allowed inside theDepsservice (shared/deps.ts).- Lazy-loaded modules are exposed as signals via
toSignal(from(...)). - All other code must import statically at the top of the file.
- Use native control flow (
@if,@for,@switch) — never*ngIf,*ngFor,*ngSwitch. - Keep templates simple; move complex logic into the component class.
- Use Angular
animate.enter/animate.leaveattributes for transition animations. - Do NOT use
ngClassorngStyle— use nativeclass/stylebindings. - Do not assume browser globals (e.g.,
new Date()) are available in templates. - Do not write arrow functions in templates.
- Use the
asyncpipe for Observables.
- Use lazy loading for all feature routes via
loadComponent:export const appRoutes: Route[] = [ { path: '', loadComponent: () => import('./home/home').then((m) => m.Home), }, ];
- Lazy-loaded import paths point directly to the
.tsfile (no barrel, no/index).
-
Always use resolvers (
ResolveFn) to load data required by a route before the component renders. Never fetch critical route data inside the component itself. -
Use the functional
ResolveFnpattern (not class-based resolvers):import { inject } from '@angular/core'; import type { ActivatedRouteSnapshot, ResolveFn, RouterStateSnapshot } from '@angular/router'; import { UserStore } from '../../shared/user-store'; import type { User } from '../../shared/types'; export const userResolver: ResolveFn<User> = (route: ActivatedRouteSnapshot, _state: RouterStateSnapshot) => { const userStore = inject(UserStore); const userId = route.paramMap.get('id')!; return userStore.getUser(userId); };
-
File naming: resolver files follow the
name.resolver.tspattern (e.g.,user.resolver.ts). -
Location: place resolver files alongside the route that uses them (inside the page feature directory).
-
Configure resolvers in the
resolveproperty of the route definition:{ path: 'user/:id', loadComponent: () => import('./user/user').then((m) => m.User), resolve: { user: userResolver, }, }
-
Keep resolvers lightweight — fetch essential data only.
-
Handle errors gracefully; use
withNavigationErrorHandlerfor centralized error handling. -
Use
import typefor router types (ActivatedRouteSnapshot,ResolveFn,RouterStateSnapshot).
-
Always use guards to protect routes that require authentication, authorization, or any precondition check. Never check access inside the component itself.
-
Use the functional guard pattern (
CanActivateFn,CanDeactivateFn,CanMatchFn):import { inject } from '@angular/core'; import type { ActivatedRouteSnapshot, CanActivateFn, RouterStateSnapshot } from '@angular/router'; import { Auth } from '../../shared/auth'; export const authGuard: CanActivateFn = (_route: ActivatedRouteSnapshot, _state: RouterStateSnapshot) => { const auth = inject(Auth); return auth.isAuthenticated(); };
-
File naming: guard files follow the
name.guard.tspattern (e.g.,auth.guard.ts). -
Location: place guards in
shared/guards/when shared across routes, or alongside the feature route when specific to one page. -
Apply guards in the route definition:
{ path: 'dashboard', loadComponent: () => import('./dashboard/dashboard').then((m) => m.Dashboard), canActivate: [authGuard], }
-
Redirecting: when a guard needs to redirect, return a
UrlTreeorRedirectCommand. Never returnfalseand then programmatically navigate. -
Multiple guards on a single route are executed in array order.
-
Use
import typefor router types (CanActivateFn,ActivatedRouteSnapshot,RouterStateSnapshot).
- Use Angular's built-in
i18nattribute to mark element content for translation:<h1 i18n="@@homeHeroTitle">Architecting Scalable Systems.</h1>
- Use
i18n-{attribute}to mark attribute values for translation:<img alt="Hero illustration" i18n-alt="@@homeHeroAlt" />
- Always use custom IDs with the
@@prefix. Never rely on auto-generated IDs.
Follow the pattern @@{page}{Section}{Description}:
| Pattern | Example |
|---|---|
| Page-level | @@homeHeroTitle, @@homeHeroBadge |
| Section-specific | @@homeJourneyRole2024, @@homeWorksProject1Desc |
| Attribute binding | @@homeHeroAlt (used with i18n-alt) |
- Page prefix: lowercase page name (
home,resume,about). - Section: PascalCase section name (
Hero,Journey,Works,Features,Footer). - Description: PascalCase descriptor (
Title,Subtitle,Badge,Role2024,Project1Desc).
- Use
$localizetagged template literals for translatable strings in.tsfiles (e.g., constants, SEO metadata):const title = $localize`:@@homeNavIntroduction:Introduction`;
- The syntax is
$localize`:@@customId:Default text`. @angular/localize/initpolyfill is already configured inproject.json.
- Run
pnpm nx run website:extract-i18nto generate the translation source file. - Translation files follow Angular's XLIFF format.
- Each component has a companion
.cssfile (even if empty); never delete it. - Use component CSS for:
- Keyframe animations (
@keyframes) - Element-level styles that cannot be expressed as Tailwind utilities (e.g.,
canvaselement sizing) @starting-styletransitions
- Keyframe animations (
- Animations are referenced from templates via
animate.enter/animate.leaveattribute names that map to CSS class names.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Home } from './home';
describe('Home', () => {
let component: Home;
let fixture: ComponentFixture<Home>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Home],
}).compileComponents();
fixture = TestBed.createComponent(Home);
component = fixture.componentInstance;
await fixture.whenStable();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});import { TestBed } from '@angular/core/testing';
import { Deps } from './deps';
describe('Deps', () => {
let service: Deps;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(Deps);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});pnpm nx g @nx/angular:component apps/web/app/src/app/admin/some-feature/some-featureGenerated components must be adjusted to follow all the conventions above (e.g., remove Component suffix, remove standalone: true, adjust file names, etc.).
- Tailwind is the primary styling tool. Use utility classes directly in templates.
- Never use raw CSS variables for colors or design tokens. Define them inside
@themeblocks instyles.css. - Use
@utilityto define custom utilities. - Dark mode uses the
darkvariant, which is configured as@custom-variant dark (&:where(.dark, .dark *)).
@importfont packages first, then Tailwind, then icon libraries.- Define global design tokens inside
@theme. - Define reusable utilities with
@utility.
Follow Screaming Architecture — folder names reveal what the app does, not what framework concepts it uses:
apps/web/app/src/app/
├── app.ts # Root component
├── app.html / app.css # Root template & styles
├── app.config.ts # Client providers
├── app.config.server.ts # Server providers
├── app.routes.ts # Client routes
├── app.routes.server.ts # Server routes (SSR)
├── admin/
│ ├── admin.routes.ts # Lazy route group for /admin
│ ├── admin-shell/
│ ├── auth/
│ │ ├── session.ts
│ │ └── sign-in/password/
│ ├── dashboard/
│ ├── metrics/
│ └── visits/
├── not-found/ # Application-wide fallback
├── shared/ # Cross-cutting concerns
│ └── layout/ # Reusable layout components
└── ui/ # App UI directives and components
- Never create top-level
services/,models/, orcomponents/directories that mix multiple domains. - Group Angular routes, their components, resolvers, and tests by feature. Place feature-specific auth and layouts with the feature. Group child routes in a feature
*.routes.tswhen the feature has its own route tree. - Reusable layout components live under
shared/layout/. - Shared services live directly in
shared/. - Constants live under
shared/constants/.
- Smart (pages): Connected to services, handle state and routing.
- Dumb (ui/layout): Receive data via
input(), emit events viaoutput(). Reusable and logic-free.
- Never deep-import files from another feature's private directory.
- Use public services or shared interfaces.
- Prettier handles formatting: 120 char width, single quotes, trailing commas, 2-space indentation.
- HTML files are parsed with the
angularparser. - ESLint rules are defined in
eslint.config.mjs; always runpnpm nx lint <project>to verify.
- Must pass all AXE checks.
- Must follow WCAG AA minimums: focus management, color contrast, ARIA attributes.
- Use
NgOptimizedImagefor all static images (does not apply to base64 images).
- Mobile-first approach, then desktop.
- Use semantic HTML5 elements.