Skip to content

Instantly share code, notes, and snippets.

@darcyclarke
Last active December 21, 2024 10:15
Show Gist options
  • Save darcyclarke/8e74147df5415a1f327ff3a1763c3fb3 to your computer and use it in GitHub Desktop.
Save darcyclarke/8e74147df5415a1f327ff3a1763c3fb3 to your computer and use it in GitHub Desktop.
Dynamic Package Install & Import
import { spawnSync } from 'node:child_process'
import { resolve } from 'node:path'
const name = 'lodash'
const opts = {
cwd: './tmp'
}
const { status } = spawnSync('npm', ['install', name], opts)
if (status !== 0) {
throw new Error('Failed to install package')
}
const { stdout } = spawnSync('npm', ['query', `#${name}`], opts)
const pkg = JSON.parse(stdout.toString())[0]
if (!pkg) {
throw new Error('Failed to get package info')
}
const path = pkg.main ? resolve(pkg.realpath, pkg.main) : pkg.realpath
const mod = await import(path)
console.log(mod)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment