Skip to content

Instantly share code, notes, and snippets.

@bradymholt
Last active November 7, 2022 13:59
Show Gist options
  • Save bradymholt/e7a467ce23b92b752340f78d6f7d343f to your computer and use it in GitHub Desktop.
Save bradymholt/e7a467ce23b92b752340f78d6f7d343f to your computer and use it in GitHub Desktop.
Require or Install NPM package on demand
/**
* This function will check to see if a module is installed and if not will run `npm install` to install all dependencies.
* Then, the module will be required and returned.
* The intended usage is for a consumer to be able to require a module even if npm install has not been run beforehand.
* Source: https://stackoverflow.com/a/53377794/626911
*
* Example usage:
* const requireOrInstall = require("./helpers/require-or-install");
* axios = await requireOrInstall("axios");
*
* @param {*} module
* @returns
*/
module.exports = async (module) => {
try {
require.resolve(module);
} catch (e) {
console.log(
`Could not resolve "${module}". Dependencies will be installed and then another attempt to resolve will be made...`
);
exec("npm install");
// Wait until the next event cycle otherwise Node will not find the module when requiring it
await new Promise((resolve) => setImmediate(() => resolve()));
}
return require(module);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment