Smarter way to organize “import” statements using “index.ts” file(s) in Angular
Angular components and modules are written in Typescript files as a module using
export keyword. As we build our Angular application to the greater extend, we end up creating many feature modules and components. We can refer a component or a module in other using “import” statement. Without “import” Typescript compiler shall throw exception for unknown type.
Consider a simple application with Login, SignUp, Dashboard, Product, Cart and Account feature. This application is routed using simple Angular routing strategy. Here is the route configuration and route graph:
Since we are using many components in
app.routing.module.ts file, we must import their reference for
.module.ts files. A general import statements would looks like this:
Even though VS Code and other smart editors resolve path for component and module still these import statements looks lengthy and cumbersome isn’t it?
Another pain point is, if we change folder structure then we must change all import statements to reflect correct path.
You may have observed
import statement used for importing packages from
@angular library. We can import more than one component, module from same import statement even though they are in different
This is possible because of
Typescript module resolution picks up
index.tsfile from folder name if it is there and try to import packages.
In this file, we can export all folder specific components and modules. For example, consider
index.ts file inside
app.routing.module.ts file, we can import all these components and module with a single statement as below.
If you notice, we are importing components and module from
./dashboard/products. Yes, we are specifying each component or module name neither we are providing
Here are the complete import statement using
index.ts file approach
Looks neat and simple, isn’t it?
Generally you should create
index.ts file in feature specific folders. But it is up to you how many
index.ts file should be created, should it be feature specific, component specific etc. This decision shall vary per application, per developer and problem statement.
Here is the GitHub repository without use of
index-demo - Simple routed Angular application without use of index.d.ts file
And here is the GitHub repository which uses
index.ts files for organizing
index-demo-solution - Using index.ts file to organize import statements.