From fa0a5a6fea71260eceda735a40133706323e4bb7 Mon Sep 17 00:00:00 2001 From: Luke Childs Date: Sun, 28 Apr 2019 15:37:18 +0700 Subject: [PATCH] Implementation --- index.js | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index f5e4978..8684dd8 100644 --- a/index.js +++ b/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(`]*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({