小程序插件是可被添加到小程序内直接使用的功能组件,在不同的小程序内叫法可能略有区别。
微信小程序、支付宝小程序中叫插件
,百度小程序中叫动态库
,方便起见,以下统一称为插件。
参考文档
- 微信小程序插件
- 支付宝小程序插件
- 百度小程序动态库
引入插件代码包
使用插件之前开发者需要在manifest.json
中的各平台对应的字段内声明使用的插件,具体配置参照所用插件的开发文档代码示例
// 微信小程序
"mp-weixin": {
"plugins": {
"myPlugin": {
"version": "1.0.0",
"provider": "wxidxxxxxxxxxxxxxxxx"
}
}
}
// 支付宝小程序
"mp-alipay": {
"myPlugin": {
"version": "*",
"provider": "2019235609092837"
}
}
// 百度小程序
"mp-baidu": {
"dynamicLib": {
"myPlugin": {
"provider": "TheUniqueNameOwnedByThisDynamicLib"
}
}
}
在页面中使用
在页面内使用插件需要在pages.json
内对应页面的style
节点下配置对应平台的usingComponents
,示例如下。
以"hello-component": "plugin://myPlugin/hello-component"
为例,key
(冒号前的hello-component
)为在页面内使用的组件名称。value
分为三段,plugin
为协议(在百度小程序内为dynamicLib
),myPlugin
为插件名称即引入插件时的名称,hello-component
为插件暴露的组件名称。// 微信小程序
{
"path": "pages/index/index",
"style": {
"mp-weixin": {
"usingComponents": {
"hello-component": "plugin://myPlugin/hello-component"
}
}
}
}
// 支付宝小程序
{
"path": "pages/index/index",
"style": {
"mp-alipay": {
"usingComponents": {
"hello-component": "plugin://myPlugin/hello-component"
}
}
}
}
// 百度小程序
{
"path": "pages/index/index",
"style": {
"mp-baidu": {
"usingComponents": {
"my-special-list": "dynamicLib://myDynamicLib/special-list"
}
}
}
}
在分包内引入插件代码包
支付宝小程序、百度小程序不支持在分包内引入插件。
此外如果项目使用了分包,在支付宝小程序内不可使用插件。
本节内容仅针对微信小程序。
如果插件只在(同一个插件不能被多个分包同时引用)一个分包用到,可以单独配置到分包中,这样插件不会随主包加载,开发者可以在pages.json
的subPackages中声明插件
代码示例
"subPackages": [{
"root": "pagesA",
"pages": [{
"path": "list/list"
}]
"plugins": {
"pluginName": {
"version": "1.0.0",
"provider": "wxidxxxxxxxxxxxxxxxx"
}
}
}]