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.
50 lines
1.4 KiB
50 lines
1.4 KiB
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');
|
|
|
|
return regex.exec(html)[0];
|
|
};
|
|
|
|
const getMetaTagContent = (metaTagHtml) => {
|
|
const regex = /content=[\"]([^\"]*)[\"]/i;
|
|
|
|
return regex.exec(metaTagHtml)[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();
|
|
|
|
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);
|
|
|
|
fs.writeFileSync(htmlPath, patchedHtml);
|
|
|
|
const end = Date.now();
|
|
spinner.stopAndPersist({
|
|
symbol: '✨ ',
|
|
text: chalk.green(`Fixed og:image link in ${prettyMs(end - start)}.`)
|
|
});
|
|
});
|
|
};
|
|
|