Last active
October 31, 2024 20:26
-
-
Save lebreRafael/1546623f730d0e93f163afadb32cb594 to your computer and use it in GitHub Desktop.
NextJS inline CSS files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Code "forked" from https://stackoverflow.com/a/66430461/4788966 | |
import Document, { | |
Main, | |
NextScript, | |
Head, | |
Html | |
} from 'next/document' | |
import {readFileSync} from "fs" | |
import {join} from "path" | |
class InlineStylesHead extends Head { | |
getCssLinks(files) { | |
const { | |
assetPrefix, | |
devOnlyCacheBusterQueryString, | |
dynamicImports, | |
optimizeFonts, | |
} = this.context | |
const cssFiles = files.allFiles.filter((file) => file.endsWith('.css')) | |
const sharedFiles = new Set(files.sharedFiles) | |
// Unmanaged files are CSS files that will be handled directly by the | |
// webpack runtime (`mini-css-extract-plugin`). | |
let dynamicCssFiles = dedupe(dynamicImports.filter((file) => file.endsWith('.css'))) | |
if (dynamicCssFiles.length) { | |
const existing = new Set(cssFiles) | |
dynamicCssFiles = dynamicCssFiles.filter((file) => !(existing.has(file) || sharedFiles.has(file))) | |
cssFiles.push(...dynamicCssFiles) | |
} | |
let cssLinkElements = [] | |
cssFiles.forEach((file) => { | |
cssLinkElements.push( | |
<style | |
key={file} | |
data-href={`${assetPrefix}/_next/${encodeURI(file)}${devOnlyCacheBusterQueryString}`} | |
dangerouslySetInnerHTML={{ | |
__html: readFileSync(join(process.cwd(), '.next', file), 'utf-8'), | |
}} | |
/> | |
) | |
}) | |
if (process.env.NODE_ENV !== 'development' && optimizeFonts) { | |
cssLinkElements = this.makeStylesheetInert(cssLinkElements) | |
} | |
return cssLinkElements.length === 0 ? null : cssLinkElements | |
} | |
} | |
function dedupe(bundles) { | |
const files = new Set() | |
const kept = [] | |
for (const bundle of bundles) { | |
if (files.has(bundle)) continue | |
files.add(bundle) | |
kept.push(bundle) | |
} | |
return kept | |
} | |
export default class MyDocument extends Document { | |
render() { | |
return ( | |
<Html lang="ru" dir="ltr"> | |
<InlineStylesHead/> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment