Last active
December 20, 2018 15:33
-
-
Save apaleslimghost/e5cce61f37fc1161bff80c1438a2a813 to your computer and use it in GitHub Desktop.
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
const npx = require('libnpx') | |
const which = require('which-promise') | |
const path = require('path') | |
const actualPackageName = req => req.split('/', req[0] === '@' ? 2 : 1).join('/') | |
module.exports = (requireName, version = 'latest') => { | |
try { | |
return Promise.resolve(require(requireName)) | |
} catch(_) { | |
return which('npm').then(npm => { | |
const args = npx.parseArgs([], npm) | |
const packageName = actualPackageName(requireName) | |
const requirePath = requireName.replace(new RegExp(`^${packageName}(/|$)`), '') | |
return npx._ensurePackages(`${packageName}@${version}`, args).then(({added, updated}) => { | |
const pkg = added.concat(updated).find(({name}) => name === packageName) | |
return require(path.join(pkg.path, requirePath)) | |
}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment