website creator Path aliases simplify paths by giving a link to the path rather than using the the full relative path.
// before: import { SharedModule } from '../../shared/shared.module'; import { DatePipe } from '../../../date.pipe'; import { environment } from '../../../environments/environment'; // after: import { SharedModule } from '@shared/shared.module'; import { DatePipe } from '@shared/pipes/date.pipe'; import { environment } from '@env/environment';
Path aliases are relative to compilerOptions.baseUrl. By default this is set to "./" so all path aliases we create must be fully qualified from the baseUrl.
Create the Aliases
This documentation uses a json program to modify the tsconfig.json file to simplify editing for everyone.
Run this command to install the json program:
json --version || sudo npm install -g json json -f tsconfig.json -I -c "this.baseUrl = './'" json -f tsconfig.json -I -c "this.compilerOptions.paths = {}" json -f tsconfig.json -I -e "this.compilerOptions.paths['@app/*'] = ['src/app/*']" json -f tsconfig.json -I -e "this.compilerOptions.paths['@core/*'] = ['src/app/core/*']" json -f tsconfig.json -I -e "this.compilerOptions.paths['@shared/*'] = ['src/app/shared/*']" json -f tsconfig.json -I -e "this.compilerOptions.paths['@env/*'] = ['src/environments/*']"
After our changes:
/* globally accessible app code (in every feature module) */ import { SomeSingletonService } from '@app/core'; import { environment } from '@env/environment'; /* localy accessible feature module code, always use relative path */ import { ExampleService } from './example.service';
tsconfig.json after the execution of the CLI commands:
{ "compilerOptions": { ..., "baseUrl": "./", "paths": { "@app/*": [ "src/app/*" ], "@core/*": [ "src/app/core/*" ], "@shared/*": [ "src/app/shared/*" ], "@env/*": [ "src/environments/*" ] } } }