-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
69 lines (62 loc) · 2.45 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
'use strict';
const fs = require('fs');
const path = require('path');
const log = require('fancy-log');
const chalk = require('chalk');
const cleanCss = require('clean-css');
const penthouse = require('penthouse');
const denodeify = require('denodeify');
const mkdirp = denodeify(require('mkdirp'));
const writeFile = denodeify(fs.writeFile);
const PLUGIN_NAME = 'penthouse-pages';
/**
* Generate multiple critical css files for given pages array
* @param {Object} options - plugin options merged with penthouse options
* @param {Object[]|String[]} options.pages - array of pages, each page can be a string or an objects
* @param {String} options.pages[].name - page name, used for dest filename
* @param {String} options.pages[].url - page url
* @param {String} options.baseUrl - base url common for all pages
* @param {String} options.dest - destination directory
*/
module.exports = (options) => {
options = Object.assign({
pages: [],
baseUrl: '',
dest: '',
cleanCssOptions: {},
}, options);
return new Promise(async (resolve) => {
for (let i = 0; i < options.pages.length; i++) {
let page = options.pages[i];
// convert page string into object
if (typeof page === 'string') {
page = {
name: page,
url: page,
}
}
// replace "/", e.g. "about/contacts" -> "about-contacts"
page.name = page.name.replace('/', '-');
// add css extension, if no one specified, .e.g. "about-contacts" -> "about-contacts.css"
if (path.extname(page.name) === '') {
page.name = page.name + '.css';
}
await penthouse(Object.assign({
url: options.baseUrl + page.url,
}, options))
.then((criticalCss) => {
let output = new cleanCss(options.cleanCssOptions).minify(criticalCss);
let filePath = path.join(options.dest, page.name);
return mkdirp(options.dest)
.then(() => writeFile(filePath, output.styles))
})
.then(() => {
log(PLUGIN_NAME + ':', chalk.green('✔ ') + page.name + chalk.gray(` from ${options.baseUrl + page.url}`));
})
.catch((err) => {
throw err;
});
}
resolve();
});
};