javascriptnode.jsvue.jsnuxt.jsatomic-design

How can I dynamically export components in index.js?


I'm working on a project with nuxt.js and I want to implement the atomic design methodology

so I currently import the components like this

import ButtonStyled from '@/components/atoms/ButtonStyled.vue'
import TextLead from '@/components/atoms/TextLead.vue'
import InputSearch from '@/components/atoms/InputSearch.vue'

but I need to import like this

import {
    ButtonStyled,
    TextLead,
    InputSearch
} from '@/components/atoms'

the closer I got was that,

/atoms/index.js
const req = require.context('./', true, /\.vue$/)

const modules = {}

req.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  modules[componentName] = req(fileName).default
})

export const { ButtonStyled, TextLead } = modules

but I'm still defining the export variable names statically, I need to define dynamics based on the components inside the folder

NOTE: I can not use

export default modules

if I use the above code snippet I will not be able to import the way I need it, which is:

import { ButtonStyled } from "@/components/atoms"

Solution

  • I created a library that does all this for me, maybe it helps other people.

    named-exports