Autogenerated module loading and ES6
When creating great applications it is important to provide systems that allow features to be implemented and maintained as discrete units of code.
It is also important to avoid magic runtime binding where functionality is implied by folder structure or some other magic variables or constants.
ES6 modules have come along and they are a great way to organise JavaScript code. They are declarative and statically analysable. Very importantly what you see is what you get.
However they lack the ability to autoload modules on the fly based on a dynamic folder structure such as the kind you would see in a modular framework that needs to bind dynamic packages of code together.
It is for this reason I created the Indexr open source project.
What Indexr does is it takes a folder, searches for any 'module' folders based on globs you provide and generates index files that export all the 'submodules' within the 'module' folders in whatever way you choose.
Installation
$ npm install -g indexr
Usage
Let's look at an example:
$ indexr . \
--out reducers.js \
--modules **/modules/ \
--submodules */reducer.js \
--direct-import
--named-exports
This example does the following:
- Use the current folder as a root folder
- Find module folders nested within this root folder that have the name
modules
- Within each
modules
folder find subfolder that contains anreducer.js
file - Create an ES6
reducers.js
file within each 'modules' folder that directly imports the submodule'sreducer.js
file. - Export the reducers as named exports.
You can also do the same thing via Node API
import indexr from 'indexr';
indexr(__dirname, {
outputFilename: 'reducers.js',
modules: '**/modules/',
submodules: '*/reducer.js',
directImport: true,
namedExports: true,
});