Setup typescript alias and barrels
Typescript alias are very useful to avoid importing modules like this
import { UserService } from '../../services/user.service';
with alias we can import like this
import { UserService } from '@services';
How to add an alias
In tsconfig.ts
you can add ad many alias you need eg:
{
compilerOptions: {
"paths": {
"@app/*": ["app/*"],
"@env/*": ["environments/*"],
"@assets/*": ["assets/*"],
"@shared/*": ["app/shared/*"],
"@models/*": ["app/models/*"],
"@services/*": ["app/services/*"],
"@constants": ["app/constants/constants.ts"],
"@carbon-design/*": ["app/shared/carbon-design/*"]
}
}
}
Barrels
Barrels are an handy way to export multiple modules from one module / file that will work like proxy eg:
you have some services:
app/services/service-one.service.ts
app/services/service-two.service.ts
instead of importing like this, specifing the exact filename and using multiple lines of code
import { ServiceOne } from '@services/service-one.service';
import { ServiceTwo } from '@services/service-two.service';
we can define a barrel in eg app/services/index.ts
with this content
export * from './service-one';
export * from './service-two';
and then we can import (using the alias too) like this (a lot faster and clear)
import { ServiceOne, ServiceTwo } from '@services/index';
Last updated
Was this helpful?