javascript – how to generate an index.js for each build – WebPack

Question:

I'm working on a nuxt/vue.js project and applying the atomic design methodology, so I'll have a lot of components, in different folders, example:

├── components
│   ├── quarks
│   │   └── ...
│   ├── bosons
│   │   └── GridLayout.vue
│   │   └── ...
│   ├── atoms
│   │   └── ButtonStyle.vue
│   │   └── InputStyle.vue
│   │   └── ...
│   ├── molecules
│   │   └── ...
│   ├── organisms
│   │   └── ...
│   ├── templates
│   │   └── ...
└─────

I would like to do named imports, for example:

import { ButtonStyle, InputStyle } from '@/components/atoms/'

but for this to work I would need to have an index.js inside each folder exporting component by component, for example

├── components
│   ├── atoms
│   │   └── ButtonStyle.vue
│   │   └── InputStyle.vue
│   │   └── index.js
└─────

e no index.js

export { default as ButtonStyled } from './ButtonStyled.vue'
export { default as InputStyle } from './InputStyle.vue'

then everything works!

But doing this work manually can be a very tiring task… Every time you create, delete, rename a component, you would have to update the index.js of its respective folder.

So I think about doing this export dynamically.

I thought about creating a Webpack Plugin and using Hooks to run some script for each build (que acontece quando um arquivo é alterado) that does this job of scanning the folders inside components and generating an index.js pra cada pasta exporting them components.

But I have no idea how to make this script…

can anybody help me?

Thanks in advance!

Answer:

I used a hook that is executed only once in the compilation, with chokidar I keep listening for changes inside my components directory.

compiler.hooks.entryOption.tap('MyPlugin', (context, entry) => {
  // generates index.js
  // Watch a directory with chokidar 
});

As I will use this in several projects, I turned it into a library, a plugin for webpack, whoever wants to, follow the link!

Webback Plugin – named-exports

Scroll to Top