entry-loader
dir-loader lets you dynamically require a directory in webpack.
In other words, dir-loader is a code-generation tool; it obviates the need to hard-code require
's for a given directory's modules and subdirectories.
contents
install
npm install --save-dev dir-loader
use
Suppose you have a webpack project with a semantic directory structure. You want to require your content but still preserve the hierarchical information inherent to the filesystem.
.
├── website
│ ├── intro.md
| |
│ ├── travel
│ │ ├── post1.md
│ │ ├── post2.md
│ │ └── post3.md
| |
│ ├── food
│ │ └── post1.md
| |
│ └──ignore-me.js
|
|
|
├── blog.config.js
└── entry.js
In a js file, specify the configuration for dir-loader:
module.exports = {
path: "./website",
filter: /\.md$/
}
And then just require that configuration with dir! in your application code!
var blog = require("dir!./blog.config.js");
...
This is equivalent to the following javascript:
var blog = {
"food": require("./website/food/post1.md"),
"intro.md": require("./website/intro.md"),
"travel": require("./website/travel/post1.md")
};
...
api
var blog = require("dir!./blog.config.js");
...
module.exports = {
path: "./website",
filter: /\.md$/,
dirFilter: /^(?!__private__).*/,
pathTransform: (_) => "bundle!" + _
}
examples
Code here.
To run it:
git clone https://github.com/sleep/dir-loader
cd dir-loader
npm install
npm run example
alternatives
dir-loader was created due to insuffciencies with require.context
,
webpack's built-in solution for dynamic requires.
require.context
provides a flat array of matched modules. This is the easiest way to dynamically require modules if your modules are non-hierarchical. But in the case you want to use the hierarchical information implicit in the filesystem structure, require.context
falls short.