猿问

将变量ES5动态导出到ES6

我正在研究vue / nuxt.js项目,想应用原子设计方法,我想以集群化和更智能的方式导入组件。


现在


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

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

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

我多么希望


import {

    ButtonStyled,

    TextLead,

    InputSearch

} from '@/components/atoms'

解决方案?


index.js 在以下文件夹中 atoms


它运行完美(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:我无法导出对象,因为无法使用,import {ButtonStyled}否则导入后必须解构对象


我需要导出以便可以使用


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

我需要导出文件夹中每个组件的名称


任何建议,信息或建议,将不胜感激。


拉莫斯之舞
浏览 166回答 2
2回答

忽然笑

首先,在EM6上使用导入/导出时,您需要小心,因为现在您无法导出js文件顶级范围之外的任何位置,并且它的一般处理方式与EM5不同。现在有了问题。我看到您正在从ForEach循环/函数内部导出组件,并且在EM5中完全可以正常工作,但与EM6完全不同,并且至少在不期望组件数量的情况下,我看到了两种解决问题的方法迅速增长:调用一个返回组件并导出它的函数,对每个组件执行此操作。应该看起来像这样:./componentsFile.jsexports.component1 = () => { /*code...*/ return component }exports.component2 = () => { /*code...*/ return component }./renderingFile.jsimport { component1, component2 } from './componentsFile.js'/* use the components that you get from the return... */另一种方法是构建一个对象,其中的字段是组件。并在导入时对其进行销毁。./componentsFile.js     const component1 = /*Create the component*/     const component2 = /*Create the component*/     exports.object = {         component1,         component2,}./renderingFile.js   import { component1, component2 } from './componentsFile.js'   /*Use the components...*/我认为您可以通过以下两种方式来获得想法。

慕无忌1623718

我创建了一个库,为我解决了这个问题,使导出从目录中命名,并侦听模块的创建,重命名和排除,并更新了执行导出的index.js。也许对其他人有帮助。命名出口
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答