egg icon indicating copy to clipboard operation
egg copied to clipboard

egg插件扩展开发,无法实现自定义插件进行使用。

Open oneWalker opened this issue 6 years ago • 1 comments

What happens?

利用eggjs进行相关的插件开发,发现还是只能自定义挂载到原有项目的application,context对象,无法在application,context上面对整个插件进行实际的挂载。

Mini Showcase Repository(REQUIRED)

  • 插件目录 `

  • lib

    • plugin
      • plugindemo
        • extend -application.js
        • app.js
        • package.json `
  • 相关例子定义

//app.js里面的自定义
module.exports = app => {
    app.testData='hello';
    app.pluginDemo = pluginName;
};

class pluginName
{
 constructor(){
    this.testData='hello';
 }
  async testSend(msg)
  {
      console.log(msg);
      return msg;
  }
}

//项目controller里面进行相关的引用
'use strict';

const Controller = require('egg').Controller;

class FooController extends Controller { 
    async plugintest()
    {
        const {ctx,app} = this;
       //正确可以获取到
        const data1 = await app.testData; 
        //错误,无法获取到该值
        const data2 = await app.pluginDemo.testData;
       //错误,无法使用该函数
        const res1 = await app.testSend("test");
        ctx.body= ‘test’;
    }
}

module.exports = FooController;

  • 插件引用 //config/plugin.js
'use strict';
const path = require('path')
/** @type Egg.EggPlugin */
module.exports = {
    pluginDemo: {
        enable: true,
        path: path.resolve(__dirname,`../lib/plugins/pluginDemo`)
    }
};

Context

  • Node Version:v12.16.1
  • Egg Version:"^2.15.1"
  • Plugin Name:自定义plugin

oneWalker avatar Apr 13 '20 06:04 oneWalker

找到问题了,class定义的是一个静态文件,需要初始化为类。

//app.js里面的自定义
module.exports = app => {
    app.testData='hello';
    app.pluginDemo =  new pluginName();
};

class pluginName
{
 constructor(){
    this.testData='hello';
 }
  async testSend(msg)
  {
      console.log(msg);
      return msg;
  }
}

oneWalker avatar Apr 13 '20 07:04 oneWalker