Barrel files

To use or not to use ?

Adrian Fâciu

developer

Barrel files ?

What are those ?

We now have modules ...

export class Foo {
    bar() {}
}

export const foo = 'bar';

export default bar = { foo: 1 };

... and imports

import defaultExport from './my-module';

import * as name from './my-module';

import { foo } from './my-module';

Barrel files

Barrel files are a way to re-export all or some exports from one, single, convenient place

How do they look

How do they look

How do they look

export { AppService } from './app.service';

export { LoggerService } from './logger.service';

export { UserService } from './user.service';

export * from './user.service';

And then instead of

import { AppService }
    from '../services/app.service';

import { LoggerService }
    from '../services/logger.service';

import { UserService }
    from '../services/user.service';

 we can have

import {
    AppService,
    LoggerService,
    UserService,
 } from '../services/index';

 and even

import {
    AppService,
    LoggerService,
    UserService,
 } from '../services';

Bonus

Paths, alias and baseUrl

module.exports = {
  //...
  resolve: {
    alias: {
      core: 
        path.resolve(__dirname,
            'src/app/core'),
    }
  }
};
"compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "core/*": ["src/app/core/*"],
    }

And then we can

import { UserService }
    from '../../../../../core/services';



import { UserService }
    from 'app/core/services';



import { UserService }
    from 'core/services';

What works and what not

"Barrel files are awesome, I'll create one in each folder"

NO

- No longer understand anything 

- Circular dependencies

- Lot of time needed to create and maintain

Avoid circular dependencies

YES

One level of barrel files

Project structure

Have one barrel file in each of those type folders

import { DocumentModel, CommentModel }
    from 'app/+documents/models';

Everything should be clear and easy to find

If it’s not, the structure and/or barrel files are wrong and should be changed

If you want the written form there is a medium post

Questions ?

Barrel files

By Adrian Faciu

Barrel files

  • 744