Simplify Your Code with TypeScript Barrels

Christoph Miksche
2 min readDec 5, 2022

--

A TypeScript Barrel is a way to simplify the importing of multiple exports from a single module.

Imagine you have a module called myModule that has several exports, such as:

export const foo = 1;
export const bar = 2;
export const baz = 3;

To import these exports into another module, you would normally have to write something like this:

import { foo, bar, baz } from './myModule';

This can get tedious if you have a large number of exports, and it can also make your code less readable. This is where TypeScript Barrels come in.

Instead of importing each export individually, you can create a “barrel” file that re-exports all of the exports from myModule. This barrel file would look like this:

export * from './myModule';

Now, in any module that wants to import the exports from myModule, you can simply write:

import * as myModule from './myModule';

This will import all of the exports from myModule into an object called myModule, which you can then use in your code like this:

myModule.foo; // 1
myModule.bar; // 2
myModule.baz; // 3

Using a barrel file can make your code more concise and easier to read, especially if you have a lot of exports in your module. It also allows you to group your exports together in a logical way, which can make it easier to manage your code.

In addition to exporting multiple exports from a single module, you can also use barrels to export multiple modules from a single barrel file. For example, you could create a barrel file called myLib that exports several different modules, like this:

export * from './module1';
export * from './module2';
export * from './module3';

Then, in any module that wants to import these exports, you can simply write:

import * as myLib from './myLib';

This will import all of the exports from the modules module1, module2, and module3 into an object called myLib, which you can then use in your code like this:

myLib.module1.foo; // 1
myLib.module2.bar; // 2
myLib.module3.baz; // 3

As you can see, TypeScript Barrels are a powerful tool for organizing and importing your modules. They can make your code more concise, easier to read, and easier to manage. If you’re not already using barrels in your TypeScript code, I highly recommend giving them a try.

--

--

Christoph Miksche

Software Developer and Investor from Germany. Writing about Software, Tech and Investments.