forked from Eliepse/parcel-plugin-metaimage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (75 loc) · 2.41 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
const fs = require('fs');
const path = require('path');
const url = require('url');
const ora = require('ora');
const chalk = require('chalk');
const prettyMs = require('pretty-ms');
const glob = require('glob');
const getMetaTag = (html, property) => {
const regex = new RegExp(
`<meta[^>]*(property|name)=["|']${property}["|'][^>]*>`,
'i'
);
const regexExec = regex.exec(html);
if (regexExec) {
return regexExec[0];
}
return false;
};
const getMetaTagContent = metaTagHtml => {
const regex = /content=["]([^"]*)["]/i;
const regexExec = regex.exec(metaTagHtml);
if (regexExec) {
return regexExec[1];
}
return false;
};
module.exports = bundler => {
bundler.on('buildEnd', async () => {
const spinner = ora(chalk.grey('Fixing meta tags image links')).start();
const start = Date.now();
glob.sync(`${bundler.options.outDir}/**/*.html`).forEach(file => {
const htmlPath = path.resolve(file);
const html = fs.readFileSync(htmlPath).toString();
let patchedHtml = html;
const ogUrlTag = getMetaTag(html, 'og:url');
const ogImageTag = getMetaTag(html, 'og:image');
const twitterImageTag = getMetaTag(html, 'twitter:image');
if (ogUrlTag) {
const ogUrlContent = getMetaTagContent(ogUrlTag);
if (ogImageTag) {
const ogImageContent = getMetaTagContent(ogImageTag);
const absoluteOgImageUrl = url.resolve(ogUrlContent, ogImageContent);
const ogImageTagAbsoluteUrl = ogImageTag.replace(
ogImageContent,
absoluteOgImageUrl
);
patchedHtml = patchedHtml.replace(ogImageTag, ogImageTagAbsoluteUrl);
}
if (twitterImageTag) {
const twitterImageContent = getMetaTagContent(twitterImageTag);
const absoluteTwitterImageUrl = url.resolve(
ogUrlContent,
twitterImageContent
);
const twitterImageTagAbsoluteUrl = twitterImageTag.replace(
twitterImageContent,
absoluteTwitterImageUrl
);
patchedHtml = patchedHtml.replace(
twitterImageTag,
twitterImageTagAbsoluteUrl
);
}
}
fs.writeFileSync(htmlPath, patchedHtml);
});
const end = Date.now();
spinner.stopAndPersist({
symbol: '✨ ',
text: chalk.green(
`Fixed meta tags image links in ${prettyMs(end - start)}.`
)
});
});
};