vue相关:require.context引入多个文件
在vue-cli项目中,可能会需要统一引入多个组件,这时候可以使用require.context,这是webpack的一个功能,具体文档见require.context,这里做简要说明:
其使用方式如下:
require.context(
directory,
(useSubdirectories = true),
(regExp = /^\.\/.*$/),
(mode = 'sync')
);
需要注意的一点是,上述的参数必须都是字面值,而不能由变量拼接而成。
require.context返回一个特殊的对象,可以以以下的方式遍历:
const cache = {};
function importAll(r) {
r.keys().forEach((key) => (cache[key] = r(key))); // 注意r(key)这种方式,不是对象取值
}
importAll(require.context('../components/', true, /\.js$/));
// At build-time cache will be populated with all required modules.