Dependencies
Modules often depend on a package that only some projects need, or that the user is expected to install themselves. Rather than assuming the package is there, or printing an install command for a package manager the user does not use, Nuxt Kit can check whether a dependency is resolvable and offer to install it with the project's own package manager.
ensureDependencyInstalled
Check that one or more dependencies are installed, prompting the user to install any that are missing.
Usage
import { defineNuxtModule, ensureDependencyInstalled } from '@nuxt/kit'
export default defineNuxtModule({
async setup () {
if (!await ensureDependencyInstalled('sass')) {
return
}
},
})
Type
function ensureDependencyInstalled (names: string, options?: EnsureDependencyInstalledOptions): Promise<boolean>
function ensureDependencyInstalled (names: string[], options?: EnsureDependencyInstalledOptions): Promise<true | string[]>
Parameters
names: One or more package names to check, and to install if they are missing.
options:
| Property | Type | Default | Description |
|---|---|---|---|
rootDir | string | nuxt.options.rootDir | Directory to resolve packages from and to install into. |
searchPaths | string[] | nuxt.options.modulesDir | Additional directories to resolve packages from. |
from | string | undefined | An extra URL or path to resolve packages from, such as import.meta.url. Useful when your own package ships the dependency as a peer dependency. |
prompt | boolean | undefined | Whether to prompt before installing. true always prompts, false never prompts (and installs automatically on StackBlitz), and leaving it unset prompts everywhere except StackBlitz. |
Return Value
Passing a single package name returns true if it is available and false if it is not. Passing an array returns true if every package is available, or an array of the package names that are still missing (because the user declined, the install failed, or there was no interactive terminal).
getAddDependencyCommand
Get the command a user should run to add dependencies to their project, using the package manager detected from cwd and falling back to npm. Use it whenever you print an install instruction, so the command matches the project's package manager.
Usage
import { defineNuxtModule, getAddDependencyCommand, useLogger } from '@nuxt/kit'
export default defineNuxtModule({
async setup (options, nuxt) {
const logger = useLogger('my-module')
const command = await getAddDependencyCommand('sass', nuxt.options.rootDir, { dev: true })
logger.warn(`\`sass\` is required. Run \`${command}\` to install it.`)
},
})
Type
function getAddDependencyCommand (names: string | string[], cwd: string, options?: { dev?: boolean }): Promise<string>
Parameters
names: One or more package names to install.
cwd: Directory to detect the package manager from.
options.dev: Whether the command should install the packages as dev dependencies.