Unverified Commit 6e4632ef authored by Janicklas Ralph's avatar Janicklas Ralph Committed by GitHub

Css optimizations (#16539)

Co-authored-by: 's avatarJJ Kasper <jj@jjsweb.site>
parent 7e387f0f
......@@ -65,6 +65,7 @@
"cookie": "0.4.1",
"cors": "2.8.5",
"coveralls": "3.0.3",
"critters": "0.0.6",
"cross-env": "6.0.3",
"cross-spawn": "6.0.5",
"escape-string-regexp": "2.0.0",
......
......@@ -728,6 +728,10 @@ export default async function getBaseWebpackConfig(
// When the 'serverless' target is used all node_modules will be compiled into the output bundles
// So that the 'serverless' bundles have 0 runtime dependencies
'@ampproject/toolbox-optimizer', // except this one
// Mark this as external if not enabled so it doesn't cause a
// webpack error from being missing
...(config.experimental.optimizeCss ? [] : ['critters']),
],
optimization: {
// Webpack 5 uses a new property for the same functionality
......@@ -969,6 +973,9 @@ export default async function getBaseWebpackConfig(
'process.env.__NEXT_OPTIMIZE_IMAGES': JSON.stringify(
config.experimental.optimizeImages
),
'process.env.__NEXT_OPTIMIZE_CSS': JSON.stringify(
!!config.experimental.optimizeCss && !dev
),
'process.env.__NEXT_SCROLL_RESTORATION': JSON.stringify(
config.experimental.scrollRestoration
),
......
......@@ -486,6 +486,7 @@ Read more: https://err.sh/next.js/export-image-api`
serverless: isTargetLikeServerless(nextConfig.target),
optimizeFonts: nextConfig.experimental.optimizeFonts,
optimizeImages: nextConfig.experimental.optimizeImages,
optimizeCss: nextConfig.experimental.optimizeCss,
})
for (const validation of result.ampValidations || []) {
......
......@@ -49,6 +49,7 @@ interface ExportPageInput {
serverless: boolean
optimizeFonts: boolean
optimizeImages: boolean
optimizeCss: any
}
interface ExportPageResults {
......@@ -68,6 +69,7 @@ interface RenderOpts {
inAmpMode?: boolean
optimizeFonts?: boolean
optimizeImages?: boolean
optimizeCss?: any
fontManifest?: FontManifest
locales?: string[]
locale?: string
......@@ -92,6 +94,7 @@ export default async function exportPage({
serverless,
optimizeFonts,
optimizeImages,
optimizeCss,
}: ExportPageInput): Promise<ExportPageResults> {
let results: ExportPageResults = {
ampValidations: [],
......@@ -250,6 +253,8 @@ export default async function exportPage({
optimizeFonts,
/// @ts-ignore
optimizeImages,
/// @ts-ignore
optimizeCss,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
......@@ -302,6 +307,9 @@ export default async function exportPage({
if (optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
curRenderOpts = {
...components,
...renderOpts,
......@@ -309,6 +317,7 @@ export default async function exportPage({
params,
optimizeFonts,
optimizeImages,
optimizeCss,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
......
......@@ -55,6 +55,7 @@ const defaultConfig: { [key: string]: any } = {
productionBrowserSourceMaps: false,
optimizeFonts: false,
optimizeImages: false,
optimizeCss: false,
scrollRestoration: false,
},
future: {
......
......@@ -151,6 +151,7 @@ export default class Server {
images: string
fontManifest: FontManifest
optimizeImages: boolean
optimizeCss: any
locale?: string
locales?: string[]
defaultLocale?: string
......@@ -207,6 +208,7 @@ export default class Server {
? requireFontManifest(this.distDir, this._isLikeServerless)
: null,
optimizeImages: this.nextConfig.experimental.optimizeImages,
optimizeCss: this.nextConfig.experimental.optimizeCss,
}
// Only the `publicRuntimeConfig` key is exposed to the client side
......@@ -275,6 +277,9 @@ export default class Server {
if (this.renderOpts.optimizeImages) {
process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
}
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
}
protected currentPhase(): string {
......
......@@ -165,9 +165,11 @@ export type RenderOptsPartial = {
optimizeFonts: boolean
fontManifest?: FontManifest
optimizeImages: boolean
optimizeCss: any
devOnlyCacheBusterQueryString?: string
resolvedUrl?: string
resolvedAsPath?: string
distDir?: string
locale?: string
locales?: string[]
defaultLocale?: string
......@@ -1038,16 +1040,35 @@ export async function renderToHTML(
}
}
html = await postProcess(
html,
{
getFontDefinition,
},
{
optimizeFonts: renderOpts.optimizeFonts,
optimizeImages: renderOpts.optimizeImages,
}
)
// Avoid postProcess if both flags are false
if (process.env.__NEXT_OPTIMIZE_FONTS || process.env.__NEXT_OPTIMIZE_IMAGES) {
html = await postProcess(
html,
{
getFontDefinition,
},
{
optimizeFonts: renderOpts.optimizeFonts,
optimizeImages: renderOpts.optimizeImages,
}
)
}
if (renderOpts.optimizeCss) {
// eslint-disable-next-line import/no-extraneous-dependencies
const Critters = require('critters')
const cssOptimizer = new Critters({
ssrMode: true,
reduceInlineStyles: false,
path: renderOpts.distDir,
publicPath: '/_next/',
preload: 'media',
fonts: false,
...renderOpts.optimizeCss,
})
html = await cssOptimizer.process(html)
}
if (inAmpMode || hybridAmp) {
// fix &amp being escaped for amphtml rel link
......
import PropTypes from 'prop-types'
import React, { Component, ReactNode, useContext } from 'react'
import React, { Component, ReactElement, ReactNode, useContext } from 'react'
import flush from 'styled-jsx/server'
import {
AMP_RENDER_TARGET,
......@@ -173,23 +173,29 @@ export class Head extends Component<
cssFiles.push(...dynamicCssFiles)
}
const cssLinkElements: JSX.Element[] = []
let cssLinkElements: JSX.Element[] = []
cssFiles.forEach((file) => {
const isSharedFile = sharedFiles.has(file)
if (!process.env.__NEXT_OPTIMIZE_CSS) {
cssLinkElements.push(
<link
key={`${file}-preload`}
nonce={this.props.nonce}
rel="preload"
href={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
as="style"
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
/>
)
}
const isUnmanagedFile = unmangedFiles.has(file)
cssLinkElements.push(
<link
key={`${file}-preload`}
nonce={this.props.nonce}
rel="preload"
href={`${assetPrefix}/_next/${encodeURI(
file
)}${devOnlyCacheBusterQueryString}`}
as="style"
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
/>,
<link
key={file}
nonce={this.props.nonce}
......@@ -205,6 +211,13 @@ export class Head extends Component<
/>
)
})
if (process.env.__NEXT_OPTIMIZE_FONTS) {
cssLinkElements = this.makeStylesheetInert(
cssLinkElements
) as ReactElement[]
}
return cssLinkElements.length === 0 ? null : cssLinkElements
}
......@@ -266,7 +279,7 @@ export class Head extends Component<
))
}
makeStylesheetInert(node: ReactNode): ReactNode {
makeStylesheetInert(node: ReactNode): ReactNode[] {
return React.Children.map(node, (c: any) => {
if (
c.type === 'link' &&
......@@ -492,12 +505,16 @@ export class Head extends Component<
href={canonicalBase + getAmpPath(ampPath, dangerousAsPath)}
/>
)}
{process.env.__NEXT_OPTIMIZE_FONTS
? this.makeStylesheetInert(this.getCssLinks(files))
: this.getCssLinks(files)}
<noscript data-n-css={this.props.nonce ?? ''} />
{!process.env.__NEXT_OPTIMIZE_CSS && this.getCssLinks(files)}
{!process.env.__NEXT_OPTIMIZE_CSS && (
<noscript data-n-css={this.props.nonce ?? ''} />
)}
{!disableRuntimeJS && this.getPreloadDynamicChunks()}
{!disableRuntimeJS && this.getPreloadMainLinks(files)}
{process.env.__NEXT_OPTIMIZE_CSS && this.getCssLinks(files)}
{process.env.__NEXT_OPTIMIZE_CSS && (
<noscript data-n-css={this.props.nonce ?? ''} />
)}
{this.context.isDevelopment && (
// this element is used to mount development styles so the
// ordering matches production
......
......@@ -5359,6 +5359,17 @@ create-hmac@^1.1.0, create-hmac@^1.1.4, create-hmac@^1.1.7:
safe-buffer "^5.0.1"
sha.js "^2.4.8"
critters@0.0.6:
version "0.0.6"
resolved "https://registry.yarnpkg.com/critters/-/critters-0.0.6.tgz#b71384113d8b5f5c82f3aeba80c122437f195d8c"
integrity sha512-NUB3Om7tkf+XWi9+2kJ2A3l4/tHORDI1UT+nHxUqay2B/tJvMpiXcklDDLBH3fPn9Pe23uu0we/08Ukjy4cLCQ==
dependencies:
chalk "^4.1.0"
css "^3.0.0"
parse5 "^6.0.1"
parse5-htmlparser2-tree-adapter "^6.0.1"
pretty-bytes "^5.3.0"
cross-env@6.0.3:
version "6.0.3"
resolved "https://registry.yarnpkg.com/cross-env/-/cross-env-6.0.3.tgz#4256b71e49b3a40637a0ce70768a6ef5c72ae941"
......@@ -5593,6 +5604,15 @@ css@^2.0.0:
source-map-resolve "^0.5.2"
urix "^0.1.0"
css@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/css/-/css-3.0.0.tgz#4447a4d58fdd03367c516ca9f64ae365cee4aa5d"
integrity sha512-DG9pFfwOrzc+hawpmqX/dHYHJG+Bsdb0klhyi1sDneOgGOXy9wQIC8hzyVp1e4NRYDBdxcylvywPkkXCHAzTyQ==
dependencies:
inherits "^2.0.4"
source-map "^0.6.1"
source-map-resolve "^0.6.0"
cssdb@^4.4.0:
version "4.4.0"
resolved "https://registry.yarnpkg.com/cssdb/-/cssdb-4.4.0.tgz#3bf2f2a68c10f5c6a08abd92378331ee803cddb0"
......@@ -11922,6 +11942,13 @@ parse-url@^5.0.0:
parse-path "^4.0.0"
protocols "^1.4.0"
parse5-htmlparser2-tree-adapter@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-6.0.1.tgz#2cdf9ad823321140370d4dbf5d3e92c7c8ddc6e6"
integrity sha512-qPuWvbLgvDGilKc5BoicRovlT4MtYT6JfJyBOMDsKoiT+GiuP5qyrPCnR9HcPECIJJmZh5jRndyNThnhhb/vlA==
dependencies:
parse5 "^6.0.1"
parse5@4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/parse5/-/parse5-4.0.0.tgz#6d78656e3da8d78b4ec0b906f7c08ef1dfe3f608"
......@@ -11930,6 +11957,11 @@ parse5@5.1.1:
version "5.1.1"
resolved "https://registry.yarnpkg.com/parse5/-/parse5-5.1.1.tgz#f68e4e5ba1852ac2cadc00f4555fff6c2abb6178"
parse5@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/parse5/-/parse5-6.0.1.tgz#e1a1c085c569b3dc08321184f19a39cc27f7c30b"
integrity sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==
parseurl@~1.3.3:
version "1.3.3"
resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4"
......@@ -13186,6 +13218,11 @@ pretty-bytes@^3.0.0:
dependencies:
number-is-nan "^1.0.0"
pretty-bytes@^5.3.0:
version "5.4.1"
resolved "https://registry.yarnpkg.com/pretty-bytes/-/pretty-bytes-5.4.1.tgz#cd89f79bbcef21e3d21eb0da68ffe93f803e884b"
integrity sha512-s1Iam6Gwz3JI5Hweaz4GoCD1WUNUIyzePFy5+Js2hjwGVt2Z79wNN+ZKOZ2vB6C+Xs6njyB84Z1IthQg8d9LxA==
pretty-format@^24.9.0:
version "24.9.0"
resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.9.0.tgz#12fac31b37019a4eea3c11aa9a959eb7628aa7c9"
......@@ -14923,6 +14960,14 @@ source-map-resolve@^0.5.0, source-map-resolve@^0.5.2:
source-map-url "^0.4.0"
urix "^0.1.0"
source-map-resolve@^0.6.0:
version "0.6.0"
resolved "https://registry.yarnpkg.com/source-map-resolve/-/source-map-resolve-0.6.0.tgz#3d9df87e236b53f16d01e58150fc7711138e5ed2"
integrity sha512-KXBr9d/fO/bWo97NXsPIAW1bFSBOuCnjbNTBMO7N59hsv5i9yzRDfcYwwt0l04+VqnKC+EwzvJZIP/qkuMgR/w==
dependencies:
atob "^2.1.2"
decode-uri-component "^0.2.0"
source-map-support@^0.5.16:
version "0.5.19"
resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.19.tgz#a98b62f86dcaf4f67399648c085291ab9e8fed61"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment