V
V
Vladimir Proskurin2016-11-13 16:19:20
JavaScript
Vladimir Proskurin, 2016-11-13 16:19:20

How to implement a plugin system in TypeScript?

Good afternoon! There is a project with the structure:
app/
---plugins/
------plugin1.ts
------plugin2.ts
------...
---main.ts
in the plugins folder there are plugins / application components that can be added later (with subsequent "recompilation" of course).
How can I import all these plugin classes into main.ts? I tried to make them a common namespace, but it does not help. The only way that helped is a crutch:

// ожидающие загрузки плагины
let waitLoad:Array<string> = [];
    // получаем все зарегестрированные модули
    for(let name in window['require'].s.contexts['_']['registry']) {
        // Если модуль находится в папке плагинов...
        if(name.slice(0, 8).toLowerCase() === 'plugins/') {
            // Добавляем его в массив ожидающих загрузку (т.к. загрузчик модулей загружает их асинхронно)
            waitLoad.push(name);
            // Импортируем модуль
            window['require']([name], function(a,b,c) {
                // удаляем из ожидающих
                waitLoad.remove(name);
                // регистрируем в самописной системе плагинов
                addFieldType(a.default);
                // если плагинов ожидающих загрузку больше нет, то вызывает событие готовности
                if(waitLoad.length === 0) {
                    onLoad();
                }
            });
        }
    }

I would just like to be able to write like this:
import * as plugins from './plugins/*';
to already plugins be an array of plugin classes. Or at least, it's more intelligent to load them into an array without asynchronous loading.
Is there any way? Or should I rethink the architecture?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2016-11-13
@Vlad_IT

let the one who adds the plugin explicitly prescribe it in the dependencies of some module. Explicit is always better than implicit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question