Skip to content

Instantly share code, notes, and snippets.

@apaleslimghost
Last active December 20, 2018 15:33
Show Gist options
  • Save apaleslimghost/e5cce61f37fc1161bff80c1438a2a813 to your computer and use it in GitHub Desktop.
Save apaleslimghost/e5cce61f37fc1161bff80c1438a2a813 to your computer and use it in GitHub Desktop.
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