/
index.ts
90 lines (75 loc) · 2.68 KB
/
index.ts
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
import { Tree } from "posthtml-parser";
import fs from "fs";
import path from "path";
import utils from "util";
import mkdirp from "mkdirp";
import favIcons, { Configuration } from "favicons";
const writeFile = utils.promisify(fs.writeFile);
export interface Options {
/** Root of resolving path to the image */
root?: string;
/**
* Directory to write the image files.
* @default "./dist"
*/
outDir?: string;
/** Cache results if orignal favicon has not changed? */
// cache?: boolean;
/** Favicon generator configuration */
configuration?: Partial<Configuration>;
}
/**
* @todo implement caching
*/
function plugin(options: Options = {}) {
const root = options.root || "./";
const outDir = options.outDir || "./dist";
// const shouldCache = options.cache === undefined ? true : options.cache;
const configuration = options.configuration || {};
return function postHtmlFavicons(tree: Tree) {
return new Promise((resolve, reject) => {
let filePath: undefined | string;
tree.match({ tag: "link", attrs: { rel: /icon/ } }, (node) => {
if (node.attrs.href === undefined) {
return node;
}
filePath = path.resolve(root, node.attrs.href);
// Remove original link tag
return false;
});
if (filePath === undefined) {
console.info("[posthtml-favicon] No favicon link tag was found.");
return resolve();
}
if (!fs.existsSync(outDir)) {
mkdirp.sync(outDir);
}
favIcons(filePath, configuration, async (err, res) => {
if (err) {
reject(err);
} else {
const writeFilePromises = [];
// Write images to disk
for (const { name, contents } of [...res.images, ...res.files]) {
writeFilePromises.push(writeFile(path.resolve(outDir, name), contents));
}
try {
await Promise.all(writeFilePromises);
} catch (e) {
return reject(e);
}
// Add tags to head tag
tree.match({ tag: "head" }, (head) => {
return {
...head,
content: [...head.content, ...res.html],
};
});
resolve(tree);
}
});
});
};
}
export default plugin;
module.exports = plugin;