require.context(directory,useSubdirectories,regExp)javascript
場景:如頁面須要導入多個組件,原始寫法:vue
import titleCom from '@/components/home/titleCom' import bannerCom from '@/components/home/bannerCom' import cellCom from '@/components/home/cellCom' components: { titleCom, bannerCom, cellCom }
樣就寫了大量重複的代碼,利用 require.context 能夠寫成java
const path = require('path') const files = require.context('@/components/home', false, /\.vue$/) const modules = {} files.keys().forEach(key => { const name = path.basename(key, '.vue') //返回文件名 不含後綴名 modules[name] = files(key).default || files(key) }) components: modules