forked from addyosmani/critical
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (80 loc) · 2.26 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* eslint-disable promise/prefer-await-to-then */
'use strict';
const path = require('path');
const through2 = require('through2');
const PluginError = require('plugin-error');
const replaceExtension = require('replace-ext');
const {create} = require('./src/core');
const {outputFileAsync} = require('./src/file');
const {getOptions} = require('./src/config');
/**
* Critical path CSS generation
* @param {object} params Options
* @param {function} cb Callback
* @return {Promise<object>} Result object with html, css & optional extracted original css
*/
async function generate(params, cb) {
try {
const options = getOptions(params);
const {target = {}, base = process.cwd()} = options;
const result = await create(options);
// Store generated css
if (target.css) {
await outputFileAsync(path.resolve(base, target.css), result.css);
}
// Store generated html
if (target.html) {
await outputFileAsync(path.resolve(base, target.html), result.html);
}
// Store extracted css
if (target.uncritical) {
await outputFileAsync(path.resolve(base, target.uncritical), result.uncritical);
}
if (typeof cb === 'function') {
cb(null, result);
return;
}
return result;
} catch (error) {
if (typeof cb === 'function') {
cb(error);
return;
}
throw error;
}
}
/**
* Streams wrapper for critical
*
* @param {object} params Critical options
* @returns {stream} Gulp stream
*/
function stream(params) {
// Return stream
return through2.obj(function (file, enc, cb) {
if (file.isNull()) {
return cb(null, file);
}
if (file.isStream()) {
return this.emit('error', new PluginError('critical', 'Streaming not supported'));
}
Promise.resolve()
.then(() => generate({...params, src: file}))
.then(({css, html}) => {
// Rename file if not inlined
if (params.inline) {
file.contents = Buffer.from(html);
} else {
file.path = replaceExtension(file.path, '.css');
file.contents = Buffer.from(css);
}
cb(null, file);
})
.catch((error) => cb(new PluginError('critical', error.message)));
});
}
generate.stream = stream;
module.exports = {
generate,
stream,
};