使用require.context 遍历文件夹里面js的所有export属性
文章目录
本文首发: https://shudong.wang/10415.html
场景
当在vuex的modules全部需要加载的时候
rematch的 models 需要全部加载的时候
在某些场景
每个再需要手动引入到 状态管理里面,我们可以做下面的优化处理
loader.js
/**
* @author stark.wang
* @blog http://shudong.wang
* The file enables `models` to import all models
* in a one-shot manner. There should not be any reason to edit this file.
*/
const files = require.context('./models', false, /\.js$/)
const models = {}
files.keys().forEach(key => {
const filename = key.replace(/(\.\/|\.js)/g, '')
models[filename] = files(key)['default']
})
export default models
在rematch使用
import models from './loader'
init({
plugins: [loadingPlugin],
models
})
在vuex里面使用
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './loader'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
export default new Vuex.Store({
modules,
strict: debug
})
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论