Last active
December 21, 2024 10:15
-
-
Save darcyclarke/8e74147df5415a1f327ff3a1763c3fb3 to your computer and use it in GitHub Desktop.
Dynamic Package Install & Import
This file contains hidden or 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
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