Skip to content

Commit

Permalink
chore: prevent fouc on dev pages (#3395)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomivirkki authored Feb 4, 2022
1 parent 7270d02 commit 5665272
Showing 1 changed file with 38 additions and 12 deletions.
50 changes: 38 additions & 12 deletions web-dev-server.config.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,50 @@
/* eslint-env node */
const fs = require('fs');

const indexFile = fs.readFileSync('./dev/index.html', 'utf8');
const preventFouc = `
<style>
body:not(.resolved) {
opacity: 0;
}
body {
transition: opacity 0.2s;
}
</style>
<script type="module">
// It's important to use type module for the script so the timing is correct
document.body.classList.add('resolved');
</script>
`;

module.exports = {
plugins: [
{
name: 'dev-page-listing',
transform(context) {
if (['/dev/index.html', '/dev', '/dev/'].includes(context.path)) {
const listing = `
<ul id="listing">
${fs
.readdirSync('./dev')
.filter((file) => file !== 'index.html')
.map((file) => `<li><a href="/dev/${file}">${file}</a></li>`)
.join('')}
</ul>`;

return { body: indexFile.replace(/<ul id="listing">.*<\/ul>/, listing) };
if (context.response.is('html')) {
let body = context.body;

// Fouc prevention
body = body.replace(/<\/body>/, `${preventFouc}\n</body>`);

// Index page listing
if (['/dev/index.html', '/dev', '/dev/'].includes(context.path)) {
const listing = `
<ul id="listing">
${fs
.readdirSync('./dev')
.filter((file) => file !== 'index.html')
.filter((file) => file.endsWith('.html'))
.map((file) => `<li><a href="/dev/${file}">${file}</a></li>`)
.join('')}
</ul>`;

body = body.replace(/<ul id="listing">.*<\/ul>/, listing);
}

return { body };
}
}
}
Expand Down

0 comments on commit 5665272

Please sign in to comment.