本文介绍我开发的一个JavaScript编写的插件化框架——MinimaJS,完全开源,源码下载地址:https://github.com/lorry2018/minimajs。该框架参考OSGi规范,将该规范定义的三大插件化功能在Node上实现了。MinimaJS三个功能:动态插件化,服务和扩展。该框架基于VSCode开发、使用ES6编码,基于Node 8开发,代码量几千行,非常的简单、优雅、轻量。框架的代码结构划分清晰,命名优雅。
我们先简单看一下,如何来使用这个框架。
1
2
3
4
5
|
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定义如下,用于声明插件的入口和出口。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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来注册一个服务。
1
2
3
4
5
6
7
8
9
|
{
"id"
:
"demoPlugin"
,
"startLevel"
: 5,
"version"
:
"1.0.0"
,
"services"
: [{
"name"
:
"logService"
,
"service"
:
"LogService.js"
}]
}
|
另一个插件,可以通过激活器来消费服务。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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轻量框架的构建,详细可以查看实例。
关于框架的问题可以加入QQ群进行讨论。
本文转自道法自然博客园博客,原文链接:http://www.cnblogs.com/baihmpgy/p/7732304.html,如需转载请自行联系原作者