javascriptnode.jsvue.jsnuxt.jsatomic-design

How to Export Variables with a Dynamic Names


I have a components folder in nuxt.js

/components/atoms/

and inside that folder I have an index.js to export all components dynamically

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

const components = {}

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

export const { ButtonStyled, TextLead, InputSearch } = components

so I can import perfectly as I wish

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

the problem is that I am defining the variables to be exported statically, fixed, so for each created component I would need to add another variable manually

I need to dynamically export the variable name

Example:

DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']

export const { DynamicCreation } = components 

// output -> export const { ButtonStyled, TextLead,InputSearch  } = components

I need to export the name of already unstructured variables

Note: I can not use this export default components because I can not import like this import { ButtonStyled } from "@/components/atoms"


Solution

  • I created a library that does this type of export, anyone who wants can install via npm

    I created a Webpack Plugin that makes named exports from a component, maybe this helps other people

    Weback Plugin - named-exports