Skip to content

Instantly share code, notes, and snippets.

@Frondor
Last active November 11, 2018 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Frondor/122607d4df80b0659ae66489c0872e58 to your computer and use it in GitHub Desktop.
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
// ./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