使用 require.context 进行批量导入,不仅可以减少代码, 后期添加新的文件不用在挨个引入。
如果你恰好使用了 webpack (或在内部使用了 webpack 的 Vue CLI 3+),那么就可以使用 require.context 只全局注册这些非常通用的基础组件。注意:
全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生。
使用 require.context 进行批量导入,不仅可以减少代码, 后期添加新的文件不用在挨个引入,引入后回调一个方法 , 该方法需传递一个文件的路径参数,得到相应的文件模块,其中有 keys 和 resovle 函数 keys 它返回一个数组,数组中所有子集都可以被 require。
context 所返回的 webpackContext 函数处理 resolve 它返回 request 被解析后得到的模块 id,其中 webpack 还有闭包 map 函数 , 该函数接受一个函数参数, 函数中默认参数包含了所有匹配的子模块的路径。
vue2 官方文档中,在应用入口文件 (比如 src/main.js) 中全局导入基础组件的示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import Vue from "vue"; import upperFirst from "lodash/upperFirst"; import camelCase from "lodash/camelCase";
const requireComponent = require.context( "./components", false, /Base[A-Z]\w+\.(vue|js)$/ );
requireComponent.keys().forEach((fileName) => { const componentConfig = requireComponent(fileName);
const componentName = upperFirst( camelCase( fileName .split("/") .pop() .replace(/\.\w+$/, "") ) );
Vue.component( componentName, componentConfig.default || componentConfig ); });
|
vuex 自动引入 modules 文件夹下的所有 js 文件(无需一个个引入)
示例:src/store/index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); import getters from "./getters";
const modulesFiles = require.context("./modules", true, /\.js$/); const modules = modulesFiles.keys().reduce((modules, modulePath) => { const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1"); const value = modulesFiles(modulePath); modules[moduleName] = value.default; return modules; }, {});
const store = new Vuex.Store({ modules, getters, });
export default store;
|