Browse Source

Implementation

pull/1/head
Luke Childs 6 years ago
parent
commit
fa0a5a6fea
  1. 27
      index.js

27
index.js

@ -1,9 +1,22 @@
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') {
@ -14,9 +27,19 @@ module.exports = bundler => {
const start = Date.now();
const htmlPath = path.join(bundler.options.outDir, 'index.html');
const html = fs.openSync(htmlPath).toString();
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);
console.log(html);
fs.writeFileSync(htmlPath, patchedHtml);
const end = Date.now();
spinner.stopAndPersist({

Loading…
Cancel
Save