赞
踩
随着项目的不断变大,可能有些人会把插件的引入和全局组件的注册都放到main.js中,导致后面main.js里面一大坨引入代码,看起来杂乱无比,也不利于后期进行维护,所以我们尽可能的让main.js看起来整洁些。此处就用到webpack的require.context功能,实现Vue自动注册全局组件及插件,方便全局组件和插件的管理。
在Vue项目开发中,经常需要import或者export各种模块,当一个页面中组件很多时,我们可能会这样引入组件:
import A from 'components/A.vue'
import B from 'components/B.vue'
import C from 'components/C.vue'
import D from 'components/D.vue'
要是每加一个组件,都要写这么一句 import ,那岂不是很蛋疼,是否可以通过自动化引入呢?
答案是肯定有的,那就要使用 webpack 给我们提供的 require.context
API:
require.context(directory, useSubdirectories, regExp)
它接收三个参数:
src/components
下包含多级子目录的组件,如下图:const requireComponent = require.context('../src/components/', true, /\w+\.(vue||js)$/)
我们可以打印一下 ctx,看返回的是什么内容:
var map = { "./A.vue": "./src/components/A.vue", "./B.vue": "./src/components/B.vue", "./C.vue": "./src/components/C.vue", "./D.vue": "./src/components/D.vue" }; function webpackContext(req) { var id = webpackContextResolve(req); return __webpack_require__(id); } function webpackContextResolve(req) { var id = map[req]; if(!(id + 1)) { // check for number or string var e = new Error("Cannot find module '" + req + "'"); e.code = 'MODULE_NOT_FOUND'; throw e; } return id; } webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = "./src/components sync recursive \\.vue$";
从打印结果可以看出,require.context执行后,返回一个方法 webpackContext,这个方法又返回一个__webpack_require__,__webpack_require__就相当于require或者import。
同时 webpackContext 还有两个静态方法 keys 与 resolve,一个 id 属性。
./src/components
这样一来,通过 ctx.keys()
我们可以得到匹配文件的相对路径数组:
["./HelloWorld.vue", "./tools/abs/bl-pua.vue", "./tools/foot.vue"]
基于以上数组,我们就可以封装一个自动引入组件的方法了,比如在 plugins
文件夹下创建 componentsRegister.js
文件:
/** * 自动注册组件 */ export default { install (Vue) { const requireComponent = require.context('../src/components/', true, /\w+\.(vue|js)$/) requireComponent.keys().forEach(fileName => { // 这个地方直接传入fileName其实就是内部会调用了resolve方法,会返回对应的文件内容(不理解可以console一下看看) const config = requireComponent(fileName); // 获取组件的 PascalCase 命名 const componentName = fileName.split('/').pop().replace(/\.\w+$/, ''); // 动态注册该目录下的所有.vue文件 // 如果这个组件选项是通过 `export default` 导出的, // 那么就会优先使用 `.default`, // 否则回退到使用模块的根。 Vue.component(componentName, config.default || config); }) } }
最后在入口文件 main.js
中导入封装好的文件,即可实现组件的自动化引入:
import Vue from 'vue'
// 自动引入处理组件插件
import componentsList from '../plugins/componentsRegister';
Vue.use(componentsList);
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。