Skip to content

Barrel in JavaScript

Last updated on February 8, 2020

Guys, this post I would like to share about the use of barrel thing which we’re using within JavaScript irrespective of the library/framework.

What is Barrel?

Before seeing usage, it’s necessary to know what’s barrel? Barrel is a container file and is represented by index.js file which exports different files together within the same folder.

Use-case

import { ForestService } from './services/forest.service.js';
import { UserService } from './services/user.service.js';
import { ThemeService } from './services/Theme.service.js';
import { UtilService } from './services/util.service.js';
import { PackageService } from './services/package.service.js';
import { RepositoryService } from './services/repository.service.js';
import { DataService } from './services/data.service.js';
import { CalculateService } from './services/calculate.service.js';
import { ImageService } from './services/image.service.js';
import { LanguageService } from './services/language.service.js';

As you see the above code snippet, it increased LOC (lines of code) for importing different files but within the same folder. To overcome this, we would end up using index.js file then we will be importing that file alone to get the referenced files.

You can check out below after done with barrel,

// index.js

export { ForestService } from '.services/forest.service.js';
export { UserService } from '.services/user.service.js';
export { ThemeService } from '.services/Theme.service.js';
export { UtilService } from '.services/util.service.js';
export { PackageService } from '.services/package.service.js';
export { RepositoryService } from '.services/repository.service.js';
export { DataService } from '.services/data.service.js';
export { CalculateService } from '.services/calculate.service.js';
export { ImageService } from '.services/image.service.js';
export { LanguageService } from '.services/language.service.js';
import { DataService,  LanguageService, CalculateService,ImageService, RepositoryService, PackageService, ThemeService, UtilService,UserService, ForestService }  from './services';

You can notice well now how it looks for readability. One thing to know here is that this doesn’t require us to mention filename explicitly ./services/index.jsas it is designed by default.

Caveat

Whatever approach even if we use, everything will have its own merits and demerits. If we heavily used barrel in an enterprise application we’ll end up definitely the issue atleast once in a while, called circular reference.

That’s totally depends on situational how we’re trying to export/import files. There is a definite way out there to fix this.

Published inAngularFrameworksJavaScriptReact