You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

6 years ago
const fs = require('fs');
const path = require('path');
6 years ago
const url = require('url');
const ora = require('ora');
const chalk = require('chalk');
6 years ago
const prettyMs = require('pretty-ms');
6 years ago
const getMetaTag = (html, property) => {
const regex = new RegExp(`<meta[^>]*property=[\"|\']${property}[\"|\'][^>]*>`, 'i');
return regex.exec(html)[0];
};
const getMetaTagContent = (metaTagHtml) => {
const regex = /content=[\"]([^\"]*)[\"]/i;
return regex.exec(metaTagHtml)[1];
};
6 years ago
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();
6 years ago
const start = Date.now();
const htmlPath = path.join(bundler.options.outDir, 'index.html');
6 years ago
const html = fs.readFileSync(htmlPath).toString();
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 = ogUrlTag.replace(ogUrlContent, absoluteOgImageUrl);
const patchedHtml = html.replace(ogImageTag, ogImageTagAbsoluteUrl);
6 years ago
6 years ago
fs.writeFileSync(htmlPath, patchedHtml);
6 years ago
const end = Date.now();
spinner.stopAndPersist({
symbol: '✨ ',
text: chalk.green(`Fixed og:image link in ${prettyMs(end - start)}.`)
});
});
6 years ago
};