webpack 的 require.context() 方法可以用于在构建时将整个目录中的文件打包成一个模块。它通常用于在 Vue 中快速注册全局组件或在 React 中快速生成路由。 具体使用方法如下:
const componentsContext = require.context('./components', true, /\.vue$/)
const components = {}
componentsContext.keys().forEach(component => {
const componentConfig = componentsContext(component)
// 使用文件名作为组件名
const componentName = component
.split('/')
.pop()
.replace(/\.\w+$/, '')
components[componentName] = componentConfig.default || componentConfig
})
例如,在 Vue 中注册全局组件:
import Vue from 'vue'
import components from './path/to/components'
Object.keys(components).forEach(name => {
Vue.component(name, components[name])
})