Search code examples
javascriptvue.jsecmascript-6nuxt.jses6-modules

Dynamic export of variables ES5 to ES6


I'm working on a vue/nuxt.js project and would like to apply the atomic design methodology, i would like to import the components in a clustered and smarter way.

currently

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

How I wish

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

Solution?

index.js in folder of atoms

it works perfectly (ES5)

// ES5 works 👍
const req = require.context('.', false, /\.vue$/)

req.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  module.exports[componentName] = req(fileName).default
})
// ES6 does not work 👎
// ERROR: Module build failed, 'import' and 'export' may only appear at the top level
const req = require.context('.', false, /\.vue$/)

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

NOTE: I can not export an object because I can not use import {ButtonStyled} or I will have to de-structure the object after importing it

I need to export so that I can use

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

I need to export name of each component in the folder

Any advice, information or suggestions will be appreciated.

Thanks in advance.


Solution

  • I created a library that solved this problem for me, makes exports named from a directory and listens to the creation, rename and exclusion of the modules and updates the index.js that does the export.

    named-exports