【发布时间】:2019-04-25 00:21:42
【问题描述】:
我正在使用 Vue.js 开发一个项目,并想应用原子设计方法,但我想以集群和更智能的方式导入组件
目前
import GridLayout from '@/components/bosons/GridLayout.vue'
import LocalStorage from '@/components/bosons/LocalStorage.vue'
import ButtonStyled from '@/components/atoms/ButtonStyled.vue'
import TextLead from '@/components/atoms/TextLead.vue'
import InputSearch from '@/components/atoms/InputSearch.vue'
import SearchForm from '@/components/molecules/SearchForm.vue'
我多么希望
import {
GridLayout,
LocalStorage
} from '@/components/bosons'
import {
ButtonStyled,
TextLead,
InputSearch
} from '@/components/atoms'
import {
SearchForm
} from '@/components/molecules'
解决方案? 我想在文件夹中放置一个 index.js
/bosons/index.js
/atoms/index.js
/molecules/index.js
并且 index.js 将导入所有组件并导出,所以它会像
import ButtonStyled from './ButtonStyled.vue'
export default {
ButtonStyled
}
或
export { default as ButtonStyled } from './ButtonStyled.vue'
工作正常,但是这种方式还是静态的,每次新建组件都需要添加index.js,每次删除组件也需要从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
如果我使用上面的代码sn-p我将无法导入我需要的方式,即:
import { ButtonStyled } from "@/components/atoms"
【问题讨论】:
-
尝试标记您使用的 javascript bundler,(我认为 Webpack 是默认的)因为您想要做的可能可以在 bundler 配置中完成。
-
这是什么意思?
but is not feasible, every component created or deleted the index.js needs to be changed- 你所说的“改变”是什么意思?我刚刚使用index.js解决方案对此进行了测试,并且效果很好。 -
@MattOestreich 这样我是静态导入的,所以对于每个创建的组件我都必须将它添加到 index.js 中,如果我删除一个组件,还需要从 index.js 中删除,我需要index.js 动态导入文件夹内的所有组件,对不起我的英语不好
-
所以你想一键自动导入项目中的每一个 Vue 文件,不管它们位于哪个目录?我绝对不建议这样做,但你为什么要首先这样做呢?
标签: javascript regex vue.js vue-component atomic-design