[Vuejs]-Import multiple components into a single line (Atomic Design + Vue.JS)

0๐Ÿ‘

โœ…

I created a Plugin Webpack, a library that is perfect for those who work with the methodology of Atomic Design, basically it makes exports named from a directory, maybe this helps other people

Weback Plugin โ€“ named-exports

0๐Ÿ‘

Here is a solution that imports all components in a folder dynamically although the import statement is two instead of one line.

Another drawback of this solution is that you would have to import the entire components folder every time, because the destructuring happens in the second line. This might lead to performance issues if you do not actually need all the components.


Step 1

I also used index files in the component folder so e.g. in your bosons folder, add an index.js file with the following content:

const req = require.context(".", false, /\.vue$/);

const components = {};

req.keys().forEach(fileName => {
  if (fileName === "./index.js") return;
  const componentName = fileName.replace(/(\.\/|\.vue)/g, "");
  components[componentName] = req(fileName).default;
});

export default components;

This adds the .vue files to the components object that you can then export. It excludes the index.js file (itself).


Step2

In your file where you want to import the boson components:

import bosons from "@/components/bosons";
const { GridLayout, LocalStorage } = bosons;

This imports the components and saves them in variables so you can use them.


Note that in my solution you cannot do

import { GridLayout, LocalStorage } from "@/components/bosons";

because the import {component} syntax looks like destructuring but isnโ€™t. It refers to the exports that look like "export const" but this is an "export default" export.

Leave a comment