进阶 oclif.io 2026-10-18 02:37:03 · 29 阅读

第34章 即时插件安装(JIT)机制详解

即时插件安装(Just-in-Time Plugin Installation) 有时,您可能希望拥有未打包在 CLI 中、而是在用户首次执行时自动安装的插件——我们称之为即时插件安装,简称 JIT。如果您希望在保持用户可访问所有插件的同时,进一步缩减 CLI 的包体积,此功能将非常有用。 启用该功能需要满足以下条件: 在 `package.json` 的 `oclif` 部分添加 `jitPlugins` 字段: "oclif": {
"jitPlugins": {
"my-plugin": "^1.2.3",
"another-plugin": "^1.2.3",
}
}
确保构建流程中包含使用 `oclif manifest` 生成清单文件的步骤。该清单会包含所有由 JIT 插件提供的命令信息,使用户无需预先安装这些插件,即可对这些命令执行 `--help` 查看帮助。若生成的清单文件未随 CLI 一起打包,该功能将无法正常工作。 实现 `jit_plugin_not_installed` 钩子。 `oclif` 致力于保持用户体验的中立性,即不强制施加特定的交互模式。凡是涉及用户交互的场景,均通过钩子(hooks)机制实现,以便您自由设计期望的用户体验。 对于 JIT 插件安装场景,可用的交互方式多种多样——您可以选择在安装前先提示用户确认,或记录特定日志消息等。 以下是实现该钩子的示例代码: import { Hook, Errors } from '@oclif/core';
import confirm from '@inquirer/confirm';

const hook: Hook.JitPluginNotInstalled = async function (opts) {
try {
const answer = await confirm({
message: `${opts.command.pluginName} not installed. Would you like to install?`
})
if (answer) {
await opts.config.runCommand('plugins:install', [`${opts.command.pluginName}@${opts.pluginVersion}`]);
}
} catch (error) {
throw new Errors.CLIError(`Could not install ${opts.command.pluginName}`, 'JitPluginInstallError');
}
};

export default hook;

评论 (0)