【发布时间】:2021-09-23 10:25:48
【问题描述】:
如何使用 require.context 添加组件? script setup 的 rfc 显示 this 示例。在示例中,每个组件都必须被导入。
在 Options API 中,我使用此代码从特定文件夹收集所有组件:
function getComponents() {
const context = require.context('../icons', true, /Icon[A-Z]\w+\.vue$/)
const res = {
components: {},
namesForValidator: [],
}
for (const key of context.keys()) {
const match = key.match(/\/(\w+)\.\w+$/)
if (match && match[1]) {
const name = kebabCase(match[1])
res.components[name] = context(key).default
res.namesForValidator.push(name)
}
}
return res
}
然后我将生成的组件对象添加到传递给 defineComponent 的选项对象中。
const { components, namesForValidator } = getIconsComponents()
export default defineComponent({
components,
// ...
})
这一切都很好。 但是我不清楚如何使它工作。 也许有(或计划)一些未记录的 defineComponets 编译器宏可以解决这个问题?
【问题讨论】:
标签: javascript webpack vuejs3 vue-sfc vue-script-setup