Do a barrel export

Import every file from a single source

Klaus Kazlauskas
2 min readApr 28, 2018

While creating modules, I've always found myself with too many paths to discover where I put a simple function. Well… Not anymore! Barrel saved my life! No one else who uses my code will wish to kill me. So, what is a barrel?

A barrel is a way to rollup exports from several modules into a single convenient module. The barrel itself is a module file that re-exports selected exports of other modules.
Source: Barasat Gitbooks

Putting those words in action, is creating an index.js file to reexport everything the end user will need:

And the end user will import everything seamlessly:

Instead of trying to reach the depths of your module:

Now, you can already create modules that won't make someone wish to kill you, or even worse, use others modules (oh the nightmares)! And now that you made the the end user's life better, I'll make yours.

Barrel with me (I'm not even sorry)

Can't I use my module file instead of a index file? Can't I export everything while importing? Is there something to generate this file for me? Can I use the exports in my own module? I'll answer all those questions, first the last one.

You can't use the barrel export inside your module

The reason is because it will cause a circle dependency. You are importing a file X from index in your Y file, and index is exporting both X and Y. This may not break your code, but prepare yourself for a warnings hell.

You can use your module as the barrel

Recently Ricardo Lino showed me the directory-named-webpack-plugin. This package lets you import a file with the same name as the folder. With this plugin, and Webpack, you can import your module in the same way as an index file: your-module/foo.

You can export while importing

You can import in one line and export in the next one, or… You can use the babel-plugin-transform-export-extensions that let you export while importing in the same line, while there is no native support for that, yet. The proposals for the native support are: Export default from and Export ns from.

There is a way to generate the barrel export file

Barrelsby is the answer you are looking for while using TypeScript. Sadly, I didn't find anything related to JavaScript, but you can colaborate with Barrelsby, or fork their project.

You can find more information and complete examples from the sources I used to create this post: Angular Glossary, Barasat Gitbooks. I hope this post helps you create a better code, as it helped me.

--

--