配置(Configuration):用户在设置里改值,插件用 API 读
配置是什么
插件在 package.json 里 声明 有哪些设置项、默认值、类型;用户在 VS Code「设置」界面或 settings.json 里 写入;插件在运行时通过 vscode.workspace.getConfiguration 读取。
通信:
- 读:插件主动
get(任意时刻)。 - 写(用户):设置 UI → VS Code 存盘 → 可选地触发
onDidChangeConfiguration通知插件(见 02-events.md)。
本项目 没有 在代码里 config.update(...) 写回设置,只有读。
在 package.json 里声明了哪些项
contributes.configuration → 节名对应代码里的 "hardwareCoreMonitor":
"configuration": {
"title": "%configuration.title%",
"properties": {
"hardwareCoreMonitor.cpuThreshold": {
"type": "number",
"default": 80,
...
},
"hardwareCoreMonitor.memoryThreshold": {
"type": "number",
"default": 85,
...
},
"hardwareCoreMonitor.refreshIntervalMs": {
"type": "number",
"default": 10000,
"minimum": 500,
...
}
}
}
完整键名 = 节.属性,例如 hardwareCoreMonitor.refreshIntervalMs。
vscode.workspace.getConfiguration 做什么
作用:拿到某一配置节的对象,再用 .get('属性名', 默认值) 读具体值。VS Code 会按用户/工作区等级 合并 后返回最终生效的值。
用法 1:监控刷新间隔
文件:src/refreshIntervalConfig.ts
export function getRefreshIntervalMs(): number {
const config = vscode.workspace.getConfiguration("hardwareCoreMonitor");
const raw = config.get<number>(
"refreshIntervalMs",
DEFAULT_REFRESH_INTERVAL_MS,
);
...
return Math.max(MIN_REFRESH_INTERVAL_MS, raw);
}
在哪里被调用:
| 调用位置 | 何时读 |
|---|---|
extension.ts → new MonitorService(getRefreshIntervalMs()) | 插件激活 |
extension.ts → startMonitoring / 侧栏可见 | 开始监控前更新间隔 |
extension.ts → onDidChangeConfiguration | 用户改 refreshIntervalMs 后 |
读完后交给 monitorService.updateInterval(...) 或构造 MonitorService,控制多久采集一次硬件。
用法 2:CPU / 内存告警阈值
文件:src/thresholdAlerter.ts
update(snapshot: MonitorSnapshot): void {
const config = vscode.workspace.getConfiguration("hardwareCoreMonitor");
const cpuThreshold = config.get<number>("cpuThreshold", 80);
const memoryThreshold = config.get<number>("memoryThreshold", 85);
在哪里被调用:extension.ts 里每次快照更新:
monitorService.onDidChangeSnapshot(
(snapshot) => {
treeProvider.update(snapshot);
statusBar.update(snapshot);
alerter.update(snapshot);
},
每次有新快照,告警器 现读 阈值再比较 CPU/内存使用率,超了就用 showWarningMessage 之类提示(仍在 thresholdAlerter.ts 内)。
用户改设置后如何传到 MonitorService
只监听 刷新间隔 这一项(不是所有配置变更都处理):
const configChangeDisposable = vscode.workspace.onDidChangeConfiguration(
(event) => {
if (
!event.affectsConfiguration("hardwareCoreMonitor.refreshIntervalMs")
) {
return;
}
monitorService.updateInterval(getRefreshIntervalMs());
},
);
event.affectsConfiguration('hardwareCoreMonitor.refreshIntervalMs'):判断这次变更是否包含本插件的 refreshIntervalMs(也可传前缀 hardwareCoreMonitor 表示整个节)。
阈值 cpuThreshold / memoryThreshold 没有 单独监听;因为每次快照 alerter.update 都会重新 get,改阈值后 下一次采集 就会用新值。
和命令、事件的关系(本项目)
用户改 refreshIntervalMs(设置 UI)
→ VS Code:onDidChangeConfiguration
→ extension.ts:getRefreshIntervalMs() + monitorService.updateInterval()
用户点「开始监控」(命令)
→ extension.ts:getRefreshIntervalMs() + monitorService.start()
配置本身不经过 TreeView;树和状态栏只消费 MonitorService 产出的快照,快照频率由上面的间隔决定。