跳到主要内容

配置项

开发插件时,你可以暴露一些配置项,让应用开发者通过 napacitor.config.json 设置它们,从而影响插件在运行时的行为。

定义配置项​

配置项放在 napacitor.config.json 的 plugins 属性下,以插件名为键:

{
"appId": "com.company.app",
"appName": "My App",
"webDir": "dist",
"plugins": {
"MyCoolPlugin": {
"style": "dark",
"iconColor": "#FF0000"
}
}
}

C# 实现通过 Config 属性(一个 JsonElement)读取插件自己的段落,并通过 AppConfig 读取整个文件:

[NapacitorPlugin("MyCoolPlugin")]
public class MyCoolPlugin : NapacitorPluginBase
{
[NapacitorMethod]
public Task<string> GetStyle()
{
if (Config.ValueKind == JsonValueKind.Object &&
Config.TryGetProperty("style", out var style) &&
style.ValueKind == JsonValueKind.String)
{
return Task.FromResult(style.GetString()!);
}
return Task.FromResult("light"); // 优雅回退
}
}

读取值​

  • Config — 对应 plugins.<PluginName>;未配置时 ValueKind 为 Undefined。
  • AppConfig — 整个 napacitor.config.json 根节点。
  • 两者都是 System.Text.Json 的 JsonElement;请使用 TryGetProperty / ValueKind 判断,而不是直接强制转换。

你无法强制使用方提供配置项,使用方也可能传入无效数据。作为插件开发者,请提供充分的文档,并在值缺失或格式错误时优雅回退。

记录配置项​

请在插件 README 中与安装说明一并记录受支持的配置项,例如:

## 配置

```json
{
"plugins": {
"MyCoolPlugin": {
"style": "dark",
"iconColor": "#FF0000"
}
}
}
```

| 选项 | 类型 | 描述 |
| --- | --- | --- |
| `style` | `'dark' \| 'light'` | 主题覆盖(默认 `'light'`)。 |
| `iconColor` | `string` | 图标颜色,`#RRGGBB`(默认 `#FFFFFF`)。 |