Node and Webpack, initialize plugins classes with require instruction

172 views Asked by At

I work with Symfony and webpack. From a javascript script, I want to manage a plugin system :

A plugin is a file containing a class and located in a specific directory "plugins". And from the main javascript script, I want to "load" all plugins ( = initialize all plugins classes) availables.

I tried the simple code :

    // In the directory 'plugins', I have by example 3 plugins files :
    // 'a.js'
    // 'b.js'
    // and 'c.js'

    // The content of each plugin is the same : 

    export class a{
        constructor(param1) {
        // ...
        }
    }

and in the main.js script :

    // ...
    // plugins is an array of string I want to load (I don't want load all module in the directory 'plugins')
    // each string is the file name of a plugin (example : a.js, c.js)
    main = this;
    main.instancesOfPlugin = [];
    plugins.forEach(function (value, index) {
        try {
            main.instancesOfPlugin[index] = new (require('./plugins/' + value))('paramfoo1');
        } catch (e) {
            if (e.code !== 'MODULE_NOT_FOUND') {
                throw e;
            }
        }
    });
    // ...

But I get an error on my browser and I don't understand why...

enter image description here

(HTMLListener refer to the main script, and the line 30 corresponds to the line main.instanceOfPlugin[index] = new (require('./plugins/' + value))('paramfoo1');)

I tried several things, but I still stuck.. thanks for any help !

1

There are 1 answers

0
spacecodeur On BEST ANSWER

The solution I found after several tries :

// a module file 
module.exports = class {

    constructor(a) {
        console.log(a);
    }

}
//and from the main script
// ...
        // plugins = ['a.js', 'c.js']
        plugins.forEach(function (value, index) {
            try {
                plugins[index] = new (require('./plugins/' + value))('paramfoo1');
            } catch (e) {
                if (e.code !== 'MODULE_NOT_FOUND') {
                    throw e;
                }
            }
        });
// ...