A barrel file makes it easier to import JavaScript code. It's an index.js
that exports all named exports from all files in its directory. This allows us to import named exports directly from that directory instead of referencing specific filenames.
The following is a barrel file located in the src/components
directory. It says to export everything contained in the files located in the src/components
directory.
export * from './Container'
export * from './Counter'
export * from './Home'
The following is a file located in the src
directory. It imports named exports exported from the index.js
file located in the components
directory.
import { Container, Counter, Home } from './components'
npm install -g create-barrel-file
Execute the following in the directory where the barrel file should be created.
create-barrel-file
In a project directory with a package.json
install create-barrel-file as a development dependency.
npm install -D create-barrel-file
Then add a script to your package json.
{
"scripts": {
"barrel": "cd some/dir && create-barrel-file && cd ../.."
}
}
Execute with npm run barrel
.