UNPKG

astro-amp

Version:

With this integration, you can convert your css file into inline code in Astro.build

89 lines 3.92 kB
import fs from 'fs'; import path from 'path'; import { fileURLToPath } from 'url'; import Console from 'colorized-log'; function isAmpPage(filePath) { const regex = /(?:^|[/\\])amp(?=[/\\]|$)/; return regex.test(filePath); } function getTime() { const now = new Date(); const hour = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); return `${hour}:${minutes}:${seconds}`; } function getTags(html, regex) { const linkTag = html.matchAll(regex); const tags = []; const refs = []; for (const link of linkTag) { tags.push(link[0]); refs.push(link[1]); } return { tags, refs }; } export default function astroCssInline() { return { name: 'astro-amp', hooks: { 'astro:build:done': async ({ dir, }) => { const url = fileURLToPath(dir); const walk = (dirPath) => fs .readdirSync(dirPath, { withFileTypes: true }) .flatMap((entry) => { const fullPath = path.join(dirPath, entry.name); return entry.isDirectory() ? walk(fullPath) : [fullPath]; }); const files = walk(url).filter((file) => file.endsWith('.html')); Console.log([ { text: ' adapting /amp files ', background: 'green' }, ]); for (const file of files) { if (isAmpPage(file)) { const html = fs.readFileSync(file, 'utf-8'); const scripts = getTags(html, /<script\s+[^>]*type\s*=\s*['"]module['"][^>]*>.*?<\/script>/g); const { tags, refs } = getTags(html, /<link[^>]*href="([^"]+\.css)"[^>]*>/g); if (tags.length > 0 && refs.length > 0) { let css = ''; let newHtml = html; refs.forEach((item, index) => { const document = path.join(url, item.replace(/^\//, '')); if (fs.existsSync(document)) { const content = fs.readFileSync(document, 'utf-8'); css = css + content + '\n'; if (index !== 0) { newHtml = newHtml.replace(tags[index], ''); } } }); newHtml = newHtml.replace(tags[0], `<style amp-custom>\n${css}\n</style>`); if (scripts.tags.length > 0) { scripts.tags.forEach((script) => { newHtml = newHtml.replace(script, ''); }); } newHtml = newHtml.replaceAll('<img', '<amp-img'); fs.writeFileSync(file, newHtml, 'utf-8'); Console.log([ { text: getTime(), color: 'black' }, { text: '[AMP]', color: 'brightBlue' }, { text: file.split('dist')[1], color: 'white', }, ]); } } } Console.log([ { text: getTime(), color: 'black' }, { text: '✓ AMP configuration completed', color: 'green' }, ]); }, }, }; } //# sourceMappingURL=index.js.map