当时的场景是将原有的前端项目加入Vuex状态管理,Vuex的好处就不用多说了
刚开始的时候每添加一个新的Store文件,需要去主的index.js去单独import,然后放到modules下,
所以就想到用webpack提供的一些全局方法来动态的引入主文件下的每一个Store文件
主要解决的问题每次建一个module需要自己去主index.js里面去注册
为了偷懒,也为了避免团队开发时同时对index.js进行修改引发冲突
所以在index.js中 动态的对子目录和模块进行注册
我的目录结构是
- store
- index
- modules
- common
- index.js
- sys
- log.js
- base
- user.js
- dept.js
- area.js
- common
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const dynamicModules = {} const files = require.context('.', true, /.js$/) const dynamicImportModules = (modules, file, splits, index = 0) => { if (index == 0 && splits[0] == 'modules') { ++index } if (splits.length == index + 1) { if ('index' == splits[index]) { modules[splits[index - 1]] = files(file).default } else { modules.modules[splits[index]] = files(file).default } } else { let tmpModules = {} if ('index' == splits[index + 1]) { tmpModules = modules } else { modules[splits[index]] = modules[splits[index]] ? modules[splits[index]] : {namespaced: true, modules: {}} tmpModules = modules[splits[index]] } dynamicImportModules(tmpModules, file, splits, ++index) } } files.keys().filter(file => file != './index.js').forEach(file => { let splits = file.replace(/(./|.js)/g, '').split('/'); dynamicImportModules(dynamicModules, file, splits) }) export default new Vuex.Store({ modules: dynamicModules, strict: process.env.NODE_ENV !== 'production' })