其实,我们可以借助一下webpack的require.context() 方法来创建自己的(模块)上下文,从而实现自动动态require组件。
我们先在components文件夹(这里面都是些高频组件)添加一个叫global.js的文件,在这个文件里使用require.context 动态将需要的高频组件统统打包进来
import Vue from 'vue'
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
const requireComponent = require.context(
'.', false, /\.vue$/
//找到components文件夹下以.vue命名的文件
)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = capitalizeFirstLetter(
fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')
//因为得到的filename格式是: './dataList.vue', 所以这里我们去掉头和尾,只保留真正的文件名
)
Vue.component(componentName, componentConfig.default || componentConfig)
})