繁体   English   中英

如何在index.js中动态导出组件?

[英]How can I dynamically export components in index.js?

我正在使用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'

我得到的更接近的是,

/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

但我仍然静态定义导出变量名称,我需要根据文件夹内的组件定义动态

注意:我不能使用

export default modules

如果我使用上面的代码片段,我将无法导入我需要它的方式,这是:

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

require.contextrequire.context中一个相当模糊的函数,运行单元测试时会遇到问题。 但是,要解决你的问题; 您需要在项目的main.js中导入index.js文件。

我是这样做的:

_globals.js

// Globally register all base components prefixed with _base for convenience, because they
// will be used very frequently. Components are registered using the
// PascalCased version of their file name.
import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context('.', true, /_base-[\w-]+\.vue$/)

requireComponent.keys().forEach(fileName => {
  const componentConfig = requireComponent(fileName)

  const componentName = upperFirst(
    camelCase(fileName.replace(/^\.\/_base/, '').replace(/\.\w+$/, ''))
  )

  Vue.component(componentName, componentConfig.default || componentConfig)
})

组件/ index.js

//...
import './_globals'
//...

main.js

//...
import './components' // This imports in the index.js
//...

这样,使用require.context()加载的组件将被注册为vue组件并使其全局可用。 我建议只使用将使用很多组件的全局组件。 如果您打算只使用一次,请不要全局加载组件。

你可以在这里找到一个有用的例子 - > https://github.com/IlyasDeckers/vuetiful/tree/master/src

要使单元测试与jest一起使用,您需要模拟require.context() 这是一个真正的痛苦,但可以通过使用babel-plugin-transform-require-context轻松实现

我尝试用你的方式做到这一点,并且知道你在module.exports上犯了一个错误
module.exports不能使用import,我想你可以这样做
at atoms / index.js

const req = require.context("./", true, /\.vue$/);
const atoms = {};
req.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, "$1");
  atoms[componentName] = req(fileName).default;
});
export default atoms;

在哪里使用

import k from "@/components/atoms/index.js";
export default {
  components: {
    test1: k.test1,
    test2: k.test2
  }
};

或index.js

import test1 from "./test1.vue";
import test2 from "./test2.vue";

export { test1, test2 };

和这样使用的地方

import {test1,test2} from "@/components/atoms/index.js";

export default {
  components: {
    test1,
    test2
  }
};

我创建了一个为我做这一切的图书馆,也许它可以帮助其他人。

命名出口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM