本文介紹我開發的一個JavaScript編寫的插件化框架——minimajs,完全開源,源碼下載地址:https://github.com/lorry2018/minimajs。該框架參考OSGi規范,將該規范定義的三大插件化功能在Node上實現了。MinimaJS三個功能:動態插件化,服務和擴展。該框架基於VSCode開發、使用ES6編碼,基於Node 8開發,代碼量幾千行,非常的簡單、優雅、輕量。框架的代碼結構划分清晰,命名優雅。
我們先簡單看一下,如何來使用這個框架。
import { Minima } from 'minimajs';
import path from 'path';
let minima = new Minima(path.join(__dirname, 'plugins'));
minima.start();
通過這幾行代碼就可以創建一個插件框架,並且從當前的plugins目錄下加載插件。
每一個插件在plugins目錄下,由plugin.json來定義插件的基本信息、依賴信息、服務和擴展,該文件必須在插件根目錄下,並且包含。一個插件由plugin.json和其它文件構成,其它文件為可選,可以包括js、html、css文件等。如下為一個插件示例。對於plugin.json文件,除了id是必填屬性,其它均為可選,這意味着最小的插件為一個只定義了plugin.json且該文件只聲明插件id。

通OSGi規范類似,每一個插件可以定義一個激活器,默認為Activator.js,如果命名不是默認值,則需要在plugin.json里面通過activator定義該激活器文件名。一個典型的Activator定義如下,用於聲明插件的入口和出口。
import { PluginContext } from 'minimajs';
export default class Activator {
constructor() {
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
}
/**
* 插件入口
*
* @param {PluginContext} context 插件上下文
* @memberof Activator
*/
start(context) {
}
/**
* 插件出口
*
* @param {PluginContext} context 插件上下文
* @memberof Activator
*/
stop(context) {
}
}
這里start與stop分別代表入口和出口,用於服務注冊、綁定、事件監聽等。
插件間通過服務進行通訊,一個插件注冊服務,一個插件消費服務。插件注冊可以通過plugin.json來聲明,也可以通過激活器start方法的PluginContext參數的addService來注冊服務。如下所示,使用plugin.json來注冊一個服務。
{
"id": "demoPlugin",
"startLevel": 5,
"version": "1.0.0",
"services": [{
"name": "logService",
"service": "LogService.js"
}]
}
另一個插件,可以通過激活器來消費服務。
import { PluginContext, log } from 'minimajs';
export default class Activator {
static logService = null;
constructor() {
this.start = this.start.bind(this);
this.stop = this.stop.bind(this);
}
/**
* 插件入口
*
* @param {PluginContext} context 插件上下文
* @memberof Activator
*/
start(context) {
let logService = context.getDefaultService('logService');
if (!logService) {
throw new Error('The logService can not be null.');
}
Activator.logService = logService;
logService.log('Get the logService successfully.');
}
stop(context) {}
}
該框架還提供了插件擴展、類加載等特性,可以通過框架提供的實例來探索。以下是一個插件化的REST框架,基於插件化構建的實例,可以通過源碼下載獲取。

這個示例演示了Express、Art-Template、WebAPI框架、插件動態擴展、Web輕量框架的構建,詳細可以查看實例。
