-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
73 lines (57 loc) · 1.9 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
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 getMetaTag = (html, property) => {
const regex = new RegExp(`<meta[^>]*property=["|']${property}["|'][^>]*>`, 'i');
const results = regex.exec(html);
if (!results) {
throw new Error(`Missing ${property}`);
}
return results[0];
};
const getMetaTagContent = metaTagHtml => {
const contentRegex = /content="([^"]*)"/i;
const results = contentRegex.exec(metaTagHtml);
if (!results) {
throw new Error(`Missing content attribute in ${chalk.bold(metaTagHtml)}`);
}
return results[1];
};
module.exports = bundler => {
bundler.on('buildEnd', async () => {
if (process.env.NODE_ENV !== 'production') {
return;
}
console.log('');
const spinner = ora(chalk.grey('Fixing og:image link')).start();
const start = Date.now();
const htmlPath = path.join(bundler.options.outDir, 'index.html');
const html = fs.readFileSync(htmlPath).toString();
let hasErrors = false;
try {
const ogImageTag = getMetaTag(html, 'og:image');
const ogImageContent = getMetaTagContent(ogImageTag);
const ogUrlTag = getMetaTag(html, 'og:url');
const ogUrlContent = getMetaTagContent(ogUrlTag);
const absoluteOgImageUrl = url.resolve(ogUrlContent, ogImageContent);
const ogImageTagAbsoluteUrl = ogImageTag.replace(ogImageContent, absoluteOgImageUrl);
const patchedHtml = html.replace(ogImageTag, ogImageTagAbsoluteUrl);
fs.writeFileSync(htmlPath, patchedHtml);
} catch (error) {
spinner.fail(error.message);
hasErrors = true;
}
const end = Date.now();
const symbol = hasErrors ? chalk.red('✖') : '✨ ';
const text = hasErrors ?
chalk.red('Failed to fix og:image link.') :
chalk.green(`Fixed og:image link in ${prettyMs(end - start)}.`);
spinner.stopAndPersist({
symbol,
text
});
});
};