Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of Concept: engines as plugins #371

Closed
wants to merge 2 commits into from
Closed

Proof of Concept: engines as plugins #371

wants to merge 2 commits into from

Conversation

awinogradov
Copy link
Member

@@ -6,7 +6,6 @@ function BEMTREE() {
BEMXJST.apply(this, arguments);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can move this to plugin constructor

@miripiruni
Copy link
Contributor

Why we can’t just add get bemxjst() here?

@awinogradov
Copy link
Member Author

@miripiruni we can) but fs. And it's not the same. The idea of this API is extending base prototype by methods from custom engines. Every next plugin gets a prev prototype and extends(overrides) its methods. It's more powerful way of usage I think.

@miripiruni
Copy link
Contributor

miripiruni commented Oct 11, 2016

The idea of this API is extending base prototype by methods from custom engines.

I don’t think we need extending more than once (like plugins composition). So can we just expose bemxjst as a require?

Like:

var Bemxjst = require('./lib/bemxjst');

var api = new Bemxjst({/* options */});
var templates = {};

api.compile(fn);
api.exportApply(templates);

return templates;

Then you can extend Bemxjst as you want and use with webpack and etc...

Copy link
Contributor

@miripiruni miripiruni left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В целом я по-прежнему скептически настроен по поводу растаскивания движка bem-xjst на разные слои.

Во-первых, это затруднит тестирование.
Во-вторых, очевидно скажется на производительности.
В-третьих, замедлит разработку — нужно будет учитывать что всё разбирается по уровням которые собираются в произвольном порядке (xjst + bem + html или xjst + html или xjst + bemtree или etc) и я думаю это того не стоит.

Я предлагаю вытащить bemxjst в get bemxjst вот сюда https://github.com/bem/bem-xjst/blob/master/index.js#L19 и дать возможность переопределять Tree.

@@ -9,6 +8,10 @@ var utils = require('./utils');

function BEMXJST(options) {
this.options = options || {};
this.options.Tree = this.options.Tree || require('./tree').Tree;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем require здесь?

require('./tree').Tree оставим во второй строке как переменную. Здесь оставим

if (this.options.Tree) Tree = this.options.Tree;.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

@@ -9,6 +8,10 @@ var utils = require('./utils');

function BEMXJST(options) {
this.options = options || {};
this.options.Tree = this.options.Tree || require('./tree').Tree;
this.options.locals = this.options.Tree.methods.concat(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Соответственно здесь и в других местах ничего не изменится.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Наверное, не стоит экстендить то, что передаётся нам по ссылке.

);
}, {fuck: 'off'});

// TODO: separate bem-methodolgy as plugin too
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Очень дикая идея. Это правда кому-то надо? На что матчится будем? Слишком много переписывать надобудет. Цепочка прототипов вырастет. Скорее всего будет медленно.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Покажу в другом PR, а может и в этом. Вай нот

"chai": "^3.5.0",
"istanbul": "^0.4.4",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ненужный дифф.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не я)

"jscs": "^3.0.3",
"jshint": "^2.7.0",
"mocha": "^3.0.2"
"mocha": "^3.0.2",
"xjst-ddsl": "github:awinogradov/xjst-ddsl#pluggable"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это временно?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, там такие же изменения просто как и в bemhtml с bemtree для примеров

constructor(templates = '', options = {}) {
this.options = options;
this.templates = [templates];
this.engine = require(`./lib/bemxjst`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

require в конструкторе не самая хорошая идея.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот это точно временно)

}

use(plugin) {
console.log(`apply engine: ${plugin.name}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это временно?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да

this.engine = plugin.engine;

const options = Object.assign(this.options, plugin.options);
const instance = new this.engine(options);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Смущает, что на каждый вызов .use() создаётся новый экземпляр this.engine()

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this.Engine() — с большой буквы, это же конструктор.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не понятно почему смущает. Комбайним конструктор перед рендером шаблонов. Сейчас мы делаем тоже самое. По факту use будет принимать массив плигнов и делать и new один раз. В текущем виде можно вынести new в apply или что-то такое.

// apply engine: bemtree
// { block: 'b', content: 'shit' }

xjst.use(bemhtml({ omg: 'bemhtml' }));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что будет если я буду писать несколько раз подряд

xjst.use(bemhtml({ omg: 'bemhtml' }));
xjst.use(bemtree({ omg: 'bemhtml' }));
xjst.use(bemhtml({ omg: 'bemhtml' }));
xjst.use(bemtree({ omg: 'bemhtml' }));

? Ведь ты предоставляешь такую возможность.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Но ведь ты сам виноват тогда.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Соглашусь с @zxqfox, ибо ты сам должен головой думать. С плагинами PostCSS таже история, никто не тестирует все возможные комбинации их порядка следования. Просто каждый должен выполнять одну законченную мысль. И да они многие из них конфликтуют из-за порядка. Это кажется нормально.

// apply engine: bemhtml
// <div class="b" id="the-id">fuckin shit</div>

xjst.use(ddsl({ omg: 'ddsl' }));
Copy link
Contributor

@miripiruni miripiruni Oct 11, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сейчас вся видимая красота конструкции use не имеет смысла, так как движки тесно связаны между собой и перекрывают методы друг друга в том порядка, в котором это предусмотрено. Написав неправильный порядок или убрав недостающий кирпич всё развалится.

По твоим кейсам этого не видно. Нужны полноценные примеры с покрытием всех вариантов.


// member templates between engine changes
this.templates.forEach(templates => {
this.compile(templates);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

При втором и последующих вызовах use() все шаблоны будут компилироваться заново, хотя это требует ощутимого времени и они уже компилировались в предыдущий раз.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Такая жизнь) Движок сменился, надо перекомпилить. Если есть идеи как лучше, то велкам

@veged veged changed the title PoC: engines as plugins Proof of Concept: engines as plugins Oct 12, 2016
@miripiruni miripiruni closed this Feb 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants