首页 > 技术文章 > 利用 webpack 的 require.context 在 vue 文件中批量导入组件

yinyuxing 2022-01-13 17:44 原文

通过下面的方法可以读取 components 文件夹下的 vue 文件并放到 map 对象中

const context = require.context('./components/', false, /\.vue$/)
const map = {}
for (const key of context.keys()) {
  // key 是文件的路径,下面的 match 是抽出文件名作为组件名
  const componentName = key.match(/\/?([^/]+)\.vue$/)
  map[componentName] = context(key)
}
console.log(map)

然后在 vue 文件的 components 配置中直接配置上面的 map

export default defineComponent({
  components: {
    componentOther, // 不在上面 map 中的组件
    ...map
  }
})

参考资料

推荐阅读