require.context('./components/', true, /\.js$/)
const ctx = require.context('./components/', true, /\.js$/)
console.log(ctx.keys())
// ["./A.js", "./B.js", "./C.js", "./D.js"]
const ctx = require.context('./components/', true, /\.js$/)
const map = {}
for (const key of ctx.keys()) {
map[key] = ctx(key)
}
console.log(map)
成功import进来了,但'./A.js'
这样的key有点不太好,自己可以处理字符串生成自己想要的key
可以优化一下,生成一个公共的方法
const importAll = context => {
const modules = {}
files.keys().forEach(key => {
const name = path.basename(key, '.vue') // 提取出用 ‘/' 隔开的path的最后一部分,path.basename(p, [ext])。 p要处理的path,ext要过滤的字符
modules[name] = files(key).default || files(key)
})
return modules
}
export default importAll
使用
import importAll from '../common/importAll'
export default importAll(require.context('./reducer', false, /\.js$/i))
第二种方法
const importAll = context => {
const modules = {}
files.keys().reduce((prev,key) => {
const name = path.basename(key, '.vue') // 提取出用 ‘/' 隔开的path的最后一部分,path.basename(p, [ext])。 p要处理的path,ext要过滤的字符
prev[name] = files(key).default || files(key)
return prev
},{})
}
export default importAll