南京响应式网站制作,网站制作 台州,个人网站做音乐网要备文化,wordpress在线人数我们项目开发中#xff0c;经常需要import或者export各种模块#xff0c;那么有没有什么办法可以简化这种引入或者导出操作呢#xff1f;答案是肯定的#xff0c;下面就为大家介绍一下require.context
require.context 是 webpack 提供的一个 API#xff0c;用于创建 con…我们项目开发中经常需要import或者export各种模块那么有没有什么办法可以简化这种引入或者导出操作呢答案是肯定的下面就为大家介绍一下require.context
require.context 是 webpack 提供的一个 API用于创建 context即一组具有相同上下文的模块。
使用 require.context 可以方便地加载多个模块并且可以灵活地控制模块的加载顺序和依赖关系。 以前我们都是通过import 方式引入组件
import A from components/A
import B from components/B
import C from components/C
import D from components/D
这样很蛋疼因为每加一个组件可能都要写这么一句这样有规律的事是否可以通过自动化完成?
require.context (需要vue-cli3的版本)
require.context(directory, useSubdirectories, regExp) directory: 要查找的文件路径useSubdirectories: 是否查找子目录regExp: 要匹配文件的正则 1.在compoents文件下随便创建index.js文件
const requireComponent require.context(./, true, /\.vue$/)
const install (Vue) {if (install.installed) returninstall.installedrequireComponent.keys().forEach(element {const config requireComponent(element)if (config config.default.name) {const componentName config.default.nameVue.component(componentName, config.default || config)}});
}if (typeof window ! undefined window.Vue) {install(window.Vue)
}export default {install
}
2.mian.js引入该js
import install from ./compoents
Vue.use(install)
总结
我们可以通过require.context可以自动化引入文件。 其实我们不单单局限于组件路由内 所有模块文件都是通用的 例如路由 接口封装模块都是可以使用的。