Last active
November 7, 2022 13:59
-
-
Save bradymholt/e7a467ce23b92b752340f78d6f7d343f to your computer and use it in GitHub Desktop.
Require or Install NPM package on demand
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
/** | |
* 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