1

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"

4

3 回答 3

0

我创建了一个执行此类导出的库,任何想要的人都可以通过安装npm

我创建了一个从组件进行命名导出的 Webpack 插件,也许这对其他人有帮助

Weback 插件 - 命名导出

于 2019-07-09T16:08:22.727 回答
0

你可以这样做,检查是否是你需要的。

创建一个文件以导入组件的组合:allComponents.js

export default {
 componentOne: require('./passToOneComponent.js');
 componentTwo: require('./passToOneComponent.js');
 componentThree: require('./passToOneComponent.js');
}

在 index.js 中导出 allComponents.js 后,使用您希望的名称:

export {default as SomeName } from 'allComponents.js';

因此,在最终文件中,您可以执行以下操作:

import { SomeName } from 'index.js';

SomeName.componentOne();
于 2019-04-25T22:59:09.310 回答
0

你应该可以这样做:

export default components

然后在您要使用组件的文件中:

import * as components from '@/components/atoms'

然后当你需要在你的 Vue 文件中使用组件时,你需要对它们进行映射:

@Component({
  components: {
    ButtonStyled: components.ButtonStyled
  }
})

现在你有:

<ButtonStyled></ButtonStyled>
于 2019-04-25T22:11:35.910 回答