DEV Community

John Peters
John Peters

Posted on

A Module's implied index.ts file

In Angular there's bit of confusion regarding modules. Angular defined it's own module (@ngModule) system, borrowing import and export keywords.

Don't be fooled; it's not the same thing as Javascript's much more simple Module system.

What is a Javascript module?

Any file containing one or more export statements is a module.

The import statement allows us to gain access to the code in that module.

Simple for sure!

The Index.ts file

When we are developing multiple components in Angular we find out after a while, that we are tired of pointing the import to each component's full path.

If we create an index.ts file in a folder of many components and export each module as shown below. Assume this is the content of the /components folder.

Index.ts under Component folder

export * from "./a";
export * from "./b";
export * from "./c";
export * from "./d";
Enter fullscreen mode Exit fullscreen mode

We now have a listing of a folder's modules.

The effect of an index.ts file

From another module in our project we are able to do this:

//Example a
import {a,b,c,d} from "/components";
Enter fullscreen mode Exit fullscreen mode

The index.ts is implied.

//Example b
import {a,b,c,d} from "/components/index.ts";
Enter fullscreen mode Exit fullscreen mode

If you are using visual studio code, when you hover over "components" in "Example a" above, you will see the index.ts file magically appear!

The disgusting thing about this is the angular.module.ts file contains almost identical information. Plus it's exports section doesn't export in the same way.

JWP 2020

Top comments (0)