Automated Module Registration
Learn how to automate the process of registering each module using Webpack's required method.
We'll cover the following...
Importing and registering every single module can be tedious and can result in many import and module registrations in the store
file. If our application was scaffolded with Vue-CLI and used Webpack internally, this process can be automated using Webpack’s require
method.
The index.js
file
Let’s create an index.js
file in the store/modules
directory with the code shown below.
Press + to interact
// Register all Vuex module by a camelCase version of their filename.import { camelCase } from "lodash-es";// Get all the filesconst requireModule = require.context(// Search for files in the current directory".",// Search for files in subdirectoriestrue,// Exclude index.js file as well as any file that has// 'Actions', 'Mutations', 'Getters', 'Types', or 'helpers' in their name.// Also, include only files that end with .js /^(?!.*(Actions|Mutations|Getters|Types|helpers|index)).*\.js$/);const modules = {};requireModule.keys().forEach(fileName => {// Ignore unit test filesif(/\.unit\.js$/.test(fileName)) return;// Remove the file extension and convert to camelcasemodules[camelCase(fileName.split("/")[1].replace(/(\.\/|\.js)/g, ""))] = {// All modules are namespacednamespaced: true,...requireModule(fileName).default,};});export default modules;
...