forked from lukechilds/parcel-plugin-ogimage
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
82 lines (71 loc) · 2.03 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
const fs = require('fs');
const path = require('path');
const url = require('url');
const glob = require('glob');
/*
* Extract a meta from a given html string
*/
const findMeta = (html, propertyName, propertyValue) => {
const regex = new RegExp(`<meta[^>]*${propertyName}=["|']${propertyValue}["|'][^>]*>`, 'i');
const regexExec = regex.exec(html);
if (regexExec) {
return regexExec[0];
}
return false;
};
/*
* Extract the content of a given meta html
*/
const getMetaTagContent = metaTagHtml => {
const regex = /content=["]([^"]*)["]/i;
const regexExec = regex.exec(metaTagHtml);
if (regexExec) {
return regexExec[1];
}
return false;
};
/*
* Change the url of a meta by prepending the given baseUrl
*/
const patchMetaToAbsolute = (metaHTML, baseUrl) => {
const metaContent = getMetaTagContent(metaHTML);
return metaHTML.replace(
metaContent,
url.resolve(baseUrl, metaContent) // Relative url to absolute url
);
};
module.exports = bundler => {
bundler.on('buildEnd', async () => {
glob.sync(`${bundler.options.outDir}/**/*.html`).forEach(file => {
const htmlPath = path.resolve(file);
let html = fs.readFileSync(htmlPath).toString();
const ogUrlTag = findMeta(html, 'property', 'og:url');
// Abort if no Opengraph url meta detected
if (!ogUrlTag) {
return;
}
// Get the base url from Opengraph meta
const ogUrl = getMetaTagContent(ogUrlTag);
// Fetch original meta
const opengraphImageMeta = findMeta(html, 'property', 'og:image');
const twitterImageMeta = findMeta(html, 'name', 'twitter:image');
// Process Opengraph meta
if (opengraphImageMeta) {
html = html.replace(
opengraphImageMeta,
patchMetaToAbsolute(opengraphImageMeta, ogUrl)
);
}
// Process Twitter meta
if (twitterImageMeta) {
html = html.replace(
twitterImageMeta,
patchMetaToAbsolute(twitterImageMeta, ogUrl)
);
}
// We write the modified html file at the end
fs.writeFileSync(htmlPath, html);
});
console.info('Fixed Opengraph and Twitter images meta tag');
});
};