Skip to content

Commit 66c5c6c

Browse files
committed
Imitate BEMHTML export behaviour
1 parent a7bd4d4 commit 66c5c6c

10 files changed

+160
-29
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ $ npm install --save-dev enb-bh
3434
* *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов (его предоставляет технология `files`). По умолчанию — `?.files`.
3535
* *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — `['bh.js']`.
3636
* *Boolean* **sourcemap** — строить карты кода.
37-
* *String* **mimic**имя переменной для экспорта.
37+
* *String|Array* **mimic**имена переменных для экспорта.
3838
* *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
3939
* *String* **jsAttrScheme** — Схема данных для параметров инициализации. По умолчанию — `js`. Форматы: `js` — Получаем `return { ... }`. `json` — JSON-формат. Получаем `{ ... }`.
4040

@@ -54,7 +54,7 @@ nodeConfig.addTech(require('enb-bh/techs/bh-client'));
5454
* *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов (его предоставляет технология `files`). По умолчанию — `?.files`.
5555
* *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — `['bh.js']`.
5656
* *Boolean* **sourcemap** — строить карты кода.
57-
* *String* **mimic**имя модуля для экспорта.
57+
* *String|Array* **mimic**имена модулей для экспорта.
5858
* *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
5959
* *String* **jsAttrScheme** — Схема данных для параметров инициализации. По умолчанию — `js`. Форматы: `js` — Получаем `return { ... }`. `json` — JSON-формат. Получаем `{ ... }`.
6060

lib/bh-client-processor.js

+11-7
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ module.exports = {
1919
* @param {Object} dependencies example: {libName: "dependencyName"}
2020
* @param {String} jsAttrName
2121
* @param {String} jsAttrScheme
22-
* @param {String} mimic
22+
* @param {String|Array} mimic
2323
* @returns {string}
2424
*/
2525
buildModule: function (targetPath, bhEngine, inputSources, dependencies, jsAttrName, jsAttrScheme,
@@ -29,7 +29,9 @@ module.exports = {
2929
this._defineModule('bh', file, dependencies, bhEngine, inputSources, jsAttrName, jsAttrScheme, true);
3030

3131
if (mimic) {
32-
this._defineModule(mimic, file, { bh: 'bh' });
32+
[].concat(mimic).forEach(function (name) {
33+
this._defineModule(name, file, { bh: 'bh' });
34+
}, this);
3335
}
3436

3537
return file;
@@ -43,7 +45,7 @@ module.exports = {
4345
* @param {String} jsAttrName
4446
* @param {String} jsAttrScheme
4547
* @param {Boolean} useSourceMap
46-
* @param {String} mimic
48+
* @param {String|Array} mimic
4749
* @returns {string}
4850
*/
4951
build: function (targetPath, bhEngine, inputSources, dependencies, jsAttrName, jsAttrScheme, useSourceMap, mimic) {
@@ -67,7 +69,7 @@ module.exports = {
6769
* @param {Object} dependencies example: {libName: "dependencyName"}
6870
* @param {String} jsAttrName
6971
* @param {String} jsAttrScheme
70-
* @param {String} [mimic]
72+
* @param {String|Array} [mimic]
7173
* @returns {Object} enb-source-map/lib/file instance
7274
*/
7375
_concatFile: function (file, bhEngine, inputSources, dependencies, jsAttrName, jsAttrScheme, mimic) {
@@ -81,9 +83,11 @@ module.exports = {
8183
file.writeLine('});');
8284

8385
if (mimic) {
84-
file.writeLine('if (typeof ' + mimic + ' === \'undefined\') {');
85-
file.writeLine('var ' + mimic + ' = bh;');
86-
file.writeLine('}');
86+
[].concat(mimic).forEach(function (name) {
87+
file.writeLine('if (typeof ' + name + ' === \'undefined\') {');
88+
file.writeLine('var ' + name + ' = bh;');
89+
file.writeLine('}');
90+
});
8791
}
8892

8993
libPrepares.forEach(function (libPrepare) {

techs/bh-client-module.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* (его предоставляет технология `files`). По умолчанию — `?.files`.
1313
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh'].
1414
* * *Boolean* **sourcemap** — строить карты кода.
15-
* * *String* **mimic** — имя модуля для экспорта.
15+
* * *String|Array* **mimic** — имена модулей для экспорта.
1616
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
1717
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `js`.
1818
* * Форматы:
@@ -35,7 +35,7 @@ module.exports = require('enb/lib/build-flow').create()
3535
.target('target', '?.bh.client.js')
3636
.defineOption('bhFile', '')
3737
.defineOption('dependencies', {})
38-
.defineOption('mimic')
38+
.defineOption('mimic', [])
3939
.defineOption('jsAttrName', 'onclick')
4040
.defineOption('jsAttrScheme', 'js')
4141
.defineOption('sourcemap', false)

techs/bh-client.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
* (его предоставляет технология `files`). По умолчанию — `?.files`.
1212
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh'].
1313
* * *Boolean* **sourcemap** — строить карты кода.
14-
* * *String* **mimic** — имя переменной для экспорта.
14+
* * *String|Array* **mimic** — имена переменных для экспорта.
1515
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
1616
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `js`.
1717
* * Форматы:
@@ -35,7 +35,7 @@ module.exports = require('enb/lib/build-flow').create()
3535
.target('target', '?.bh.client.js')
3636
.defineOption('bhFile', '')
3737
.defineOption('dependencies', {})
38-
.defineOption('mimic')
38+
.defineOption('mimic', [])
3939
.defineOption('jsAttrName', 'onclick')
4040
.defineOption('jsAttrScheme', 'js')
4141
.defineOption('sourcemap', false)

techs/bh-server-include.js

+9
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* (его предоставляет технология `files`). По умолчанию — `?.files`.
1313
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh'].
1414
* * *Boolean* **sourcemap** — строить карты кода.
15+
* * *String|Array* **mimic** — имена модулей для экспорта.
1516
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
1617
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `js`.
1718
* * Форматы:
@@ -34,6 +35,7 @@ module.exports = require('enb/lib/build-flow').create()
3435
.name('bh-server-include')
3536
.target('target', '?.bh.js')
3637
.defineOption('bhFile', '')
38+
.defineOption('mimic', [])
3739
.defineOption('jsAttrName', 'onclick')
3840
.defineOption('jsAttrScheme', 'js')
3941
.defineOption('sourcemap', false)
@@ -49,6 +51,7 @@ module.exports = require('enb/lib/build-flow').create()
4951
.builder(function (bhFiles) {
5052
var node = this.node,
5153
dependencies = {},
54+
mimic = this._mimic,
5255
jsAttrName = this._jsAttrName,
5356
jsAttrScheme = this._jsAttrScheme,
5457
sourcemap = this._sourcemap,
@@ -75,6 +78,12 @@ module.exports = require('enb/lib/build-flow').create()
7578

7679
file.writeLine('module.exports = bh;');
7780

81+
if (mimic) {
82+
[].concat(mimic).forEach(function (name) {
83+
file.writeLine('bh[\'' + name + '\'] = bh;');
84+
});
85+
}
86+
7887
return file.render();
7988
});
8089
})

techs/bh-server.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
* * *String* **filesTarget** — files-таргет, на основе которого получается список исходных файлов
1313
* (его предоставляет технология `files`). По умолчанию — `?.files`.
1414
* * *String* **sourceSuffixes** — суффиксы файлов, по которым строится `files`-таргет. По умолчанию — ['bh.js'].
15+
* * *String|Array* **mimic** — имена модулей для экспорта.
1516
* * *String* **jsAttrName** — атрибут блока с параметрами инициализации. По умолчанию — `onclick`.
1617
* * *String* **jsAttrScheme** — Cхема данных для параметров инициализации. По умолчанию — `js`.
1718
* * Форматы:
@@ -31,6 +32,7 @@ module.exports = require('enb/lib/build-flow').create()
3132
.name('bh-server')
3233
.target('target', '?.bh.js')
3334
.defineOption('bhFile', '')
35+
.defineOption('mimic', [])
3436
.defineOption('jsAttrName', 'onclick')
3537
.defineOption('jsAttrScheme', 'js')
3638
.useFileList(['bh.js'])
@@ -97,7 +99,10 @@ module.exports = require('enb/lib/build-flow').create()
9799
return buildRequire(file.fullname, '', '(bh)');
98100
}).join('\n'),
99101
'',
100-
'module.exports = bh;'
102+
'module.exports = bh;',
103+
this._mimic ? [].concat(this._mimic).map(function (name) {
104+
return 'bh[\'' + name + '\'] = bh;';
105+
}).join('\n') : ''
101106
].join('\n');
102107
})
103108
.createTech();

test/techs/bh-client-module.test.js

+37-15
Original file line numberDiff line numberDiff line change
@@ -52,23 +52,45 @@ describe('bh-client-module', function () {
5252
return runTest(test, options);
5353
});
5454

55-
it('mimic', function () {
56-
var test = [
57-
'chai.should();',
58-
'describe("bh-client-module", function () {',
59-
'it("autogenerated test", function (done) {',
60-
'modules.require("BEMHTML", function (BEMHTML) {',
61-
'BEMHTML.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
62-
'done();',
55+
describe('mimic', function () {
56+
it('mimic as a string', function () {
57+
var test = [
58+
'chai.should();',
59+
'describe("bh-client-module", function () {',
60+
'it("autogenerated test", function (done) {',
61+
'modules.require("BEMHTML", function (BEMHTML) {',
62+
'BEMHTML.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
63+
'done();',
64+
'});',
6365
'});',
64-
'});',
65-
'});'
66-
].join('\n'),
67-
options = {
68-
mimic: 'BEMHTML'
69-
};
66+
'});'
67+
].join('\n'),
68+
options = {
69+
mimic: 'BEMHTML'
70+
};
71+
72+
return runTest(test, options);
73+
});
7074

71-
return runTest(test, options);
75+
it('mimic to different template engines', function () {
76+
var test = [
77+
'chai.should();',
78+
'describe("bh-client-module", function () {',
79+
'it("autogenerated test", function (done) {',
80+
'modules.require(["BEMHTML", "render"], function (BEMHTML, render) {',
81+
'BEMHTML.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
82+
'render.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
83+
'done();',
84+
'});',
85+
'});',
86+
'});'
87+
].join('\n'),
88+
options = {
89+
mimic: ['BEMHTML', 'render']
90+
};
91+
92+
return runTest(test, options);
93+
});
7294
});
7395

7496
describe('jsAttr', function () {

test/techs/bh-client.test.js

+35
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,41 @@ describe('bh-client', function () {
6767
return runTest(test, options);
6868
});
6969

70+
describe('mimic', function () {
71+
it('mimic as a string', function () {
72+
var test = [
73+
'chai.should();',
74+
'describe("bh-client", function () {',
75+
'it("autogenerated test", function () {',
76+
'BEMHTML.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
77+
'})',
78+
'})'
79+
].join('\n'),
80+
options = {
81+
mimic: 'BEMHTML'
82+
};
83+
84+
return runTest(test, options);
85+
});
86+
87+
it('mimic to different template engines', function () {
88+
var test = [
89+
'chai.should();',
90+
'describe("bh-client", function () {',
91+
'it("autogenerated test", function () {',
92+
'BEMHTML.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
93+
'render.apply({ block: "block" }).should.equal(\'<a class="block"></a>\');',
94+
'})',
95+
'})'
96+
].join('\n'),
97+
options = {
98+
mimic: ['BEMHTML', 'render']
99+
};
100+
101+
return runTest(test, options);
102+
});
103+
});
104+
70105
describe('jsAttr', function () {
71106
it('should use dafault jsAttrName and jsAttrScheme params', function () {
72107
var test = generateTest(

test/techs/bh-server-include.test.js

+28
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,30 @@ describe('bh-server-include', function () {
8181
return assert(bemjson, html, templates);
8282
});
8383

84+
describe('mimic', function () {
85+
it('mimic to BEMHTML', function () {
86+
var templates = [
87+
'bh.match("block", function(ctx) {ctx.tag("a");});'
88+
],
89+
bemjson = { block: 'block' },
90+
html = '<a class="block"></a>',
91+
options = { mimic: 'BEMHTML' };
92+
93+
return assert(bemjson, html, templates, options);
94+
});
95+
96+
it('mimic as an array', function () {
97+
var templates = [
98+
'bh.match("block", function(ctx) {ctx.tag("a");});'
99+
],
100+
bemjson = { block: 'block' },
101+
html = '<a class="block"></a>',
102+
options = { mimic: ['BH', 'BEMHTML'] };
103+
104+
return assert(bemjson, html, templates, options);
105+
});
106+
});
107+
84108
describe('caches', function () {
85109
it('must use cached bhFile', function () {
86110
var scheme = {
@@ -254,5 +278,9 @@ function assert(bemjson, html, templates, options) {
254278
return bundle.runTechAndRequire(bhServerInclude, options)
255279
.spread(function (bh) {
256280
bh.apply(bemjson).must.be(html);
281+
282+
options && options.mimic && [].concat(options.mimic).forEach(function (name) {
283+
bh[name].apply(bemjson).must.be(html);
284+
});
257285
});
258286
}

test/techs/bh-server.test.js

+28
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,30 @@ describe('bh-server', function () {
115115
});
116116
});
117117

118+
describe('mimic', function () {
119+
it('mimic to BEMHTML', function () {
120+
var templates = [
121+
'bh.match("block", function(ctx) {ctx.tag("a");});'
122+
],
123+
bemjson = { block: 'block' },
124+
html = '<a class="block"></a>',
125+
options = { mimic: 'BEMHTML' };
126+
127+
return assert(bemjson, html, templates, options);
128+
});
129+
130+
it('mimic as an array', function () {
131+
var templates = [
132+
'bh.match("block", function(ctx) {ctx.tag("a");});'
133+
],
134+
bemjson = { block: 'block' },
135+
html = '<a class="block"></a>',
136+
options = { mimic: ['BH', 'BEMHTML'] };
137+
138+
return assert(bemjson, html, templates, options);
139+
});
140+
});
141+
118142
describe('caches', function () {
119143
it('must use cached bhFile', function () {
120144
var scheme = {
@@ -263,5 +287,9 @@ function assert(bemjson, html, templates, options) {
263287
return bundle.runTechAndRequire(bhServer, options)
264288
.spread(function (bh) {
265289
bh.apply(bemjson).must.be(html);
290+
291+
options && options.mimic && [].concat(options.mimic).forEach(function (name) {
292+
bh[name].apply(bemjson).must.be(html);
293+
});
266294
});
267295
}

0 commit comments

Comments
 (0)