how to generate an index.js for each build - Webpack

Asked

Viewed 123 times

3

I am working on a nuxt/Vue.js project and applying the Atomic design methodology, so I will have many components, in different folders, example:

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

i would like to make named imports, 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
└─────

and in the index.js

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

then everything works!

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

So I think about doing this export dynamically.

I thought of creating a Webpack Plugin and using the Hooks to run some script at each build (que acontece quando um arquivo é alterado) do this job of sweeping folders inside components and generate a index.js pra cada pasta exporting the components.

But I have no idea how to make this script..

someone could help me?

Thank you in advance!

  • 2

    Why don’t you stop creating this file index? Just import directly from the file... If you are losing productivity, I see no reason to bother doing something like this. PS: My opinion.

  • @Luizfelipe, I intend to improve in Atomic Design, for this type of architecture that has many components and many imports, it would be interesting a syntax lean at the time of making imports, because it would imports grouped by type of Component, the objective is refactoring and legibility.

  • I think what you want is an CLI type of Angular, there you have the command ng g c which creates a component and has an option where you can specify a template package (by default it uses Angular’s own, but you can put yours), do not know if Vue has a CLI, if not, can do a

1 answer

0


I used a hook that runs only once in the build, with chokidar I keep hearing changes inside my component 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 transformed it into a library, a plugin for webpack, who want, follow the link!

Weback Plugin - named-Exports

Browser other questions tagged

You are not signed in. Login or sign up in order to post.