Last active
November 25, 2021 22:42
-
-
Save NovemberDev/d765a417986262341db203b1deac6ef3 to your computer and use it in GitHub Desktop.
Vuex auto import store modules with typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This script loads and registers store modules automagically from the same folder. | |
* | |
* Assuming following setup: | |
* src/store-modules/index.ts | |
* src/store-modules/ui-store.ts | |
* | |
* Produces: | |
* store | |
* store/ui | |
* | |
* Use vue3 devtools (beta) to inspect the vuex store. | |
*/ | |
import { createStore } from 'vuex' | |
function loadStoreModules() { | |
const context = require.context('./', true, /^(?!.\/index).*\.ts/i); | |
const modules: any[] = [] | |
context.keys().forEach(key => { | |
modules.push({ | |
name: key.replace("./", "").replace("-store.ts", "").trim().toLowerCase(), | |
module: context(key).default | |
}) | |
}) | |
return modules | |
} | |
const storeModules: { [key: string]: any } = {}; | |
loadStoreModules().forEach((item) => { | |
storeModules[item.name] = item.module; | |
}); | |
export default createStore({ | |
state: { | |
}, | |
mutations: { | |
}, | |
actions: { | |
}, | |
modules: storeModules | |
}) | |
/** | |
* Sample store module: | |
* | |
* src/store-modules/ui-store.ts | |
* | |
* Code: | |
* | |
import { createStore } from "vuex" | |
export default createStore({ | |
state: { | |
hello: "world" | |
}, | |
mutations: { | |
}, | |
actions: { | |
}, | |
modules: { | |
} | |
}) | |
* | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment