UNPKG

2.19 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6
7var _postcss = require('postcss');
8
9var _postcss2 = _interopRequireDefault(_postcss);
10
11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
13/**
14 * Get the number of selectors for a given node.
15 * @param {Object} node CSS node in question.
16 * @returns {Number} Total number of selectors associated with that node.
17 */
18var getSelLength = function getSelLength(node) {
19 if (node.type === 'rule') {
20 return node.selectors.length;
21 }
22 if (node.type === 'atrule') {
23 return 1 + node.nodes.reduce(function (memo, n) {
24 return memo + getSelLength(n);
25 }, 0);
26 }
27 return 0;
28};
29
30/**
31 * PostCSS plugin that splits the generated result into multiple results based
32 * on number of selectors.
33 * @param {Number} size Maximum number of rules in a single file.
34 * @param {Function} result Options passed to `postcss.toResult()`
35 * @returns {Object} `postcss` plugin instance.
36 */
37exports.default = _postcss2.default.plugin('postcss-chunk', function () {
38 var _ref = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
39
40 var _ref$size = _ref.size;
41 var size = _ref$size === undefined ? 4000 : _ref$size;
42 var _ref$result = _ref.result;
43 var genResult = _ref$result === undefined ? function () {
44 return {};
45 } : _ref$result;
46
47 return function (css, result) {
48 var chunks = [];
49 var count = void 0;
50 var chunk = void 0;
51
52 // Create a new chunk that holds current result.
53 var nextChunk = function nextChunk() {
54 count = 0;
55 chunk = css.clone({ nodes: [] });
56 chunks.push(chunk);
57 };
58
59 // Walk the nodes. When we overflow the selector count, then start a new
60 // chunk. Collect the nodes into the current chunk.
61 css.nodes.forEach(function (n) {
62 var selCount = getSelLength(n);
63 if (!chunk || count + selCount > size) {
64 nextChunk();
65 }
66 chunk.nodes.push(n);
67 count += selCount;
68 });
69
70 // Output the results.
71 result.chunks = chunks.map(function (c, i) {
72 return c.toResult(genResult(i, c));
73 });
74 };
75});
76//# sourceMappingURL=chunk.js.map
\No newline at end of file