Last active
November 11, 2018 01:08
-
-
Save Frondor/122607d4df80b0659ae66489c0872e58 to your computer and use it in GitHub Desktop.
Use webpack's require.context to auto-load configuration files from a given directory, and resolve a singleton object with the contents from the container
This file contains 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
// ./config/app.js | |
export default { | |
version: "6.6.6" | |
} | |
// ./container.js (service container) | |
import Binder from "binder"; | |
export default new Binder(); | |
// ./index.js (app bootstrap module) | |
import container from "./container"; | |
/** | |
* Use webpack dependency managemenent with require.context | |
* https://webpack.js.org/guides/dependency-management/#require-context | |
* to auto-load configuration files from a given directory, and return | |
* a singleton object with container.get("config") | |
*/ | |
container.singleton("config", () => { | |
// NOTE: params to context must be hard-coded: | |
const files = require.context("./config/", false, /\.(js|json)$/); | |
return files.keys().reduce(function(cache, key) { | |
const configName = key | |
.split("/") | |
.pop() | |
.replace(/\.(js|json)$/, ""); | |
return (cache[configName] = files(key).default), cache; | |
}, {}); | |
}); | |
// Then you can do: | |
container.get("config").app.version // "6.6.6" | |
// You didn't need to import any file from ./config folder manually |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment