Unverified Commit 0750092c authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

add experimental.gzipSize flag which allows to switch to uncompressed sizes (#25028)

Co-authored-by: 's avatarTim Neutkens <timneutkens@me.com>
parent c1528e4f
...@@ -79,6 +79,7 @@ import { trace, setGlobal } from '../telemetry/trace' ...@@ -79,6 +79,7 @@ import { trace, setGlobal } from '../telemetry/trace'
import { import {
collectPages, collectPages,
detectConflictingPaths, detectConflictingPaths,
computeFromManifest,
getJsPageSizeInKb, getJsPageSizeInKb,
getNamedExports, getNamedExports,
hasCustomGetInitialProps, hasCustomGetInitialProps,
...@@ -724,6 +725,11 @@ export default async function build( ...@@ -724,6 +725,11 @@ export default async function build(
) )
} }
const computedManifestData = await computeFromManifest(
buildManifest,
distDir,
config.experimental.gzipSize
)
await Promise.all( await Promise.all(
pageKeys.map(async (page) => { pageKeys.map(async (page) => {
const checkPageSpan = staticCheckSpan.traceChild('check-page', { const checkPageSpan = staticCheckSpan.traceChild('check-page', {
...@@ -734,7 +740,9 @@ export default async function build( ...@@ -734,7 +740,9 @@ export default async function build(
const [selfSize, allSize] = await getJsPageSizeInKb( const [selfSize, allSize] = await getJsPageSizeInKb(
actualPage, actualPage,
distDir, distDir,
buildManifest buildManifest,
config.experimental.gzipSize,
computedManifestData
) )
let isSsg = false let isSsg = false
...@@ -1525,6 +1533,7 @@ export default async function build( ...@@ -1525,6 +1533,7 @@ export default async function build(
useStatic404, useStatic404,
pageExtensions: config.pageExtensions, pageExtensions: config.pageExtensions,
buildManifest, buildManifest,
gzipSize: config.experimental.gzipSize,
}) })
) )
......
import '../next-server/server/node-polyfill-fetch' import '../next-server/server/node-polyfill-fetch'
import chalk from 'chalk' import chalk from 'chalk'
import gzipSize from 'next/dist/compiled/gzip-size' import getGzipSize from 'next/dist/compiled/gzip-size'
import textTable from 'next/dist/compiled/text-table' import textTable from 'next/dist/compiled/text-table'
import path from 'path' import path from 'path'
import { promises as fs } from 'fs'
import { isValidElementType } from 'react-is' import { isValidElementType } from 'react-is'
import stripAnsi from 'next/dist/compiled/strip-ansi' import stripAnsi from 'next/dist/compiled/strip-ansi'
import { import {
...@@ -32,11 +33,20 @@ import * as Log from './output/log' ...@@ -32,11 +33,20 @@ import * as Log from './output/log'
import { loadComponents } from '../next-server/server/load-components' import { loadComponents } from '../next-server/server/load-components'
import { trace } from '../telemetry/trace' import { trace } from '../telemetry/trace'
const fileGzipStats: { [k: string]: Promise<number> } = {} const fileGzipStats: { [k: string]: Promise<number> | undefined } = {}
const fsStatGzip = (file: string) => { const fsStatGzip = (file: string) => {
if (fileGzipStats[file]) return fileGzipStats[file] const cached = fileGzipStats[file]
fileGzipStats[file] = gzipSize.file(file) if (cached) return cached
return fileGzipStats[file] return (fileGzipStats[file] = getGzipSize.file(file))
}
const fileSize = async (file: string) => (await fs.stat(file)).size
const fileStats: { [k: string]: Promise<number> | undefined } = {}
const fsStat = (file: string) => {
const cached = fileStats[file]
if (cached) return cached
return (fileStats[file] = fileSize(file))
} }
export function collectPages( export function collectPages(
...@@ -70,6 +80,7 @@ export async function printTreeView( ...@@ -70,6 +80,7 @@ export async function printTreeView(
pageExtensions, pageExtensions,
buildManifest, buildManifest,
useStatic404, useStatic404,
gzipSize = true,
}: { }: {
distPath: string distPath: string
buildId: string buildId: string
...@@ -77,6 +88,7 @@ export async function printTreeView( ...@@ -77,6 +88,7 @@ export async function printTreeView(
pageExtensions: string[] pageExtensions: string[]
buildManifest: BuildManifest buildManifest: BuildManifest
useStatic404: boolean useStatic404: boolean
gzipSize?: boolean
} }
) { ) {
const getPrettySize = (_size: number): string => { const getPrettySize = (_size: number): string => {
...@@ -96,7 +108,7 @@ export async function printTreeView( ...@@ -96,7 +108,7 @@ export async function printTreeView(
// Re-add `static/` for root files // Re-add `static/` for root files
.replace(/^<buildId>/, 'static') .replace(/^<buildId>/, 'static')
// Remove file hash // Remove file hash
.replace(/[.-]([0-9a-z]{6})[0-9a-z]{14}(?=\.)/, '.$1') .replace(/(?:^|[.-])([0-9a-z]{6})[0-9a-z]{14}(?=\.)/, '.$1')
const messages: [string, string, string][] = [ const messages: [string, string, string][] = [
['Page', 'Size', 'First Load JS'].map((entry) => ['Page', 'Size', 'First Load JS'].map((entry) =>
...@@ -115,7 +127,12 @@ export async function printTreeView( ...@@ -115,7 +127,12 @@ export async function printTreeView(
list = [...list, '/404'] list = [...list, '/404']
} }
const sizeData = await computeFromManifest(buildManifest, distPath, pageInfos) const sizeData = await computeFromManifest(
buildManifest,
distPath,
gzipSize,
pageInfos
)
const pageList = list const pageList = list
.slice() .slice()
...@@ -378,9 +395,10 @@ let cachedBuildManifest: BuildManifest | undefined ...@@ -378,9 +395,10 @@ let cachedBuildManifest: BuildManifest | undefined
let lastCompute: ComputeManifestShape | undefined let lastCompute: ComputeManifestShape | undefined
let lastComputePageInfo: boolean | undefined let lastComputePageInfo: boolean | undefined
async function computeFromManifest( export async function computeFromManifest(
manifest: BuildManifest, manifest: BuildManifest,
distPath: string, distPath: string,
gzipSize: boolean = true,
pageInfos?: Map<string, PageInfo> pageInfos?: Map<string, PageInfo>
): Promise<ComputeManifestShape> { ): Promise<ComputeManifestShape> {
if ( if (
...@@ -414,6 +432,8 @@ async function computeFromManifest( ...@@ -414,6 +432,8 @@ async function computeFromManifest(
}) })
}) })
const getSize = gzipSize ? fsStatGzip : fsStat
const commonFiles = [...files.entries()] const commonFiles = [...files.entries()]
.filter(([, len]) => len === expected || len === Infinity) .filter(([, len]) => len === expected || len === Infinity)
.map(([f]) => f) .map(([f]) => f)
...@@ -426,7 +446,7 @@ async function computeFromManifest( ...@@ -426,7 +446,7 @@ async function computeFromManifest(
stats = await Promise.all( stats = await Promise.all(
commonFiles.map( commonFiles.map(
async (f) => async (f) =>
[f, await fsStatGzip(path.join(distPath, f))] as [string, number] [f, await getSize(path.join(distPath, f))] as [string, number]
) )
) )
} catch (_) { } catch (_) {
...@@ -438,7 +458,7 @@ async function computeFromManifest( ...@@ -438,7 +458,7 @@ async function computeFromManifest(
uniqueStats = await Promise.all( uniqueStats = await Promise.all(
uniqueFiles.map( uniqueFiles.map(
async (f) => async (f) =>
[f, await fsStatGzip(path.join(distPath, f))] as [string, number] [f, await getSize(path.join(distPath, f))] as [string, number]
) )
) )
} catch (_) { } catch (_) {
...@@ -486,9 +506,13 @@ function sum(a: number[]): number { ...@@ -486,9 +506,13 @@ function sum(a: number[]): number {
export async function getJsPageSizeInKb( export async function getJsPageSizeInKb(
page: string, page: string,
distPath: string, distPath: string,
buildManifest: BuildManifest buildManifest: BuildManifest,
gzipSize: boolean = true,
computedManifestData?: ComputeManifestShape
): Promise<[number, number]> { ): Promise<[number, number]> {
const data = await computeFromManifest(buildManifest, distPath) const data =
computedManifestData ||
(await computeFromManifest(buildManifest, distPath, gzipSize))
const fnFilterJs = (entry: string) => entry.endsWith('.js') const fnFilterJs = (entry: string) => entry.endsWith('.js')
...@@ -507,11 +531,13 @@ export async function getJsPageSizeInKb( ...@@ -507,11 +531,13 @@ export async function getJsPageSizeInKb(
data.commonFiles data.commonFiles
).map(fnMapRealPath) ).map(fnMapRealPath)
const getSize = gzipSize ? fsStatGzip : fsStat
try { try {
// Doesn't use `Promise.all`, as we'd double compute duplicate files. This // Doesn't use `Promise.all`, as we'd double compute duplicate files. This
// function is memoized, so the second one will instantly resolve. // function is memoized, so the second one will instantly resolve.
const allFilesSize = sum(await Promise.all(allFilesReal.map(fsStatGzip))) const allFilesSize = sum(await Promise.all(allFilesReal.map(getSize)))
const selfFilesSize = sum(await Promise.all(selfFilesReal.map(fsStatGzip))) const selfFilesSize = sum(await Promise.all(selfFilesReal.map(getSize)))
return [selfFilesSize, allFilesSize] return [selfFilesSize, allFilesSize]
} catch (_) {} } catch (_) {}
......
...@@ -62,6 +62,7 @@ export type NextConfig = { [key: string]: any } & { ...@@ -62,6 +62,7 @@ export type NextConfig = { [key: string]: any } & {
reactRoot: boolean reactRoot: boolean
enableBlurryPlaceholder: boolean enableBlurryPlaceholder: boolean
disableOptimizedLoading: boolean disableOptimizedLoading: boolean
gzipSize: boolean
} }
} }
...@@ -120,6 +121,7 @@ export const defaultConfig: NextConfig = { ...@@ -120,6 +121,7 @@ export const defaultConfig: NextConfig = {
reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0, reactRoot: Number(process.env.NEXT_PRIVATE_REACT_ROOT) > 0,
enableBlurryPlaceholder: false, enableBlurryPlaceholder: false,
disableOptimizedLoading: true, disableOptimizedLoading: true,
gzipSize: true,
}, },
future: { future: {
strictPostcssConfiguration: false, strictPostcssConfiguration: false,
......
...@@ -56,7 +56,11 @@ function assignDefaults(userConfig: { [key: string]: any }) { ...@@ -56,7 +56,11 @@ function assignDefaults(userConfig: { [key: string]: any }) {
return currentConfig return currentConfig
} }
if (key === 'experimental' && value && value !== defaultConfig[key]) { if (
key === 'experimental' &&
value !== undefined &&
value !== defaultConfig[key]
) {
experimentalWarning() experimentalWarning()
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import 'flat-map-polyfill' import 'flat-map-polyfill'
import { remove } from 'fs-extra' import { remove } from 'fs-extra'
import { nextBuild } from 'next-test-utils' import { nextBuild, File } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir' import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
...@@ -10,133 +10,162 @@ jest.setTimeout(1000 * 60 * 2) ...@@ -10,133 +10,162 @@ jest.setTimeout(1000 * 60 * 2)
const fixturesDir = join(__dirname, '..', 'fixtures') const fixturesDir = join(__dirname, '..', 'fixtures')
describe('Build Output', () => { const nextConfig = new File(join(fixturesDir, 'basic-app/next.config.js'))
describe('Basic Application Output', () => {
let stdout
const appDir = join(fixturesDir, 'basic-app')
beforeAll(async () => {
await remove(join(appDir, '.next'))
})
it('should not include internal pages', async () => { describe('Build Output', () => {
;({ stdout } = await nextBuild(appDir, [], { for (const gzipSize of [true, false, undefined]) {
stdout: true, describe(
})) 'Basic Application Output' +
(gzipSize !== undefined
expect(stdout).toMatch(/\/ [ ]* \d{1,} B/) ? ` (with experimental.gzipSize: ${gzipSize})`
expect(stdout).toMatch(/\+ First Load JS shared by all [ 0-9.]* kB/) : ''),
expect(stdout).toMatch(/ chunks\/main\.[0-9a-z]{6}\.js [ 0-9.]* kB/) () => {
expect(stdout).toMatch(/ chunks\/framework\.[0-9a-z]{6}\.js [ 0-9. ]* kB/) let stdout
const appDir = join(fixturesDir, 'basic-app')
expect(stdout).not.toContain(' /_document')
expect(stdout).not.toContain(' /_app') beforeAll(async () => {
expect(stdout).not.toContain(' /_error') await remove(join(appDir, '.next'))
expect(stdout).not.toContain('<buildId>') if (gzipSize !== undefined) {
nextConfig.write(
expect(stdout).toContain('○ /') `module.exports = { experimental: { gzipSize: ${gzipSize} } };`
}) )
}
it('should not deviate from snapshot', async () => { })
console.log(stdout)
if (gzipSize !== undefined) {
if (process.env.NEXT_PRIVATE_SKIP_SIZE_TESTS) { afterAll(async () => {
return nextConfig.delete()
} })
}
const parsePageSize = (page) => it('should not include internal pages', async () => {
stdout.match( ;({ stdout } = await nextBuild(appDir, [], {
new RegExp(` ${page} .*?((?:\\d|\\.){1,} (?:\\w{1,})) `) stdout: true,
)[1] }))
const parsePageFirstLoad = (page) => expect(stdout).toMatch(/\/ [ ]* \d{1,} B/)
stdout.match( expect(stdout).toMatch(/\+ First Load JS shared by all [ 0-9.]* kB/)
new RegExp( expect(stdout).toMatch(/ chunks\/main\.[0-9a-z]{6}\.js [ 0-9.]* kB/)
` ${page} .*?(?:(?:\\d|\\.){1,}) .*? ((?:\\d|\\.){1,} (?:\\w{1,}))` expect(stdout).toMatch(
/ chunks\/framework\.[0-9a-z]{6}\.js [ 0-9. ]* kB/
) )
)[1]
const parseSharedSize = (sharedPartName) => { expect(stdout).not.toContain(' /_document')
const matches = stdout.match( expect(stdout).not.toContain(' /_app')
new RegExp(`${sharedPartName} .*? ((?:\\d|\\.){1,} (?:\\w{1,}))`) expect(stdout).not.toContain(' /_error')
) expect(stdout).not.toContain('<buildId>')
expect(stdout).toContain('○ /')
})
it('should not deviate from snapshot', async () => {
console.log(stdout)
if (process.env.NEXT_PRIVATE_SKIP_SIZE_TESTS) {
return
}
const parsePageSize = (page) =>
stdout.match(
new RegExp(` ${page} .*?((?:\\d|\\.){1,} (?:\\w{1,})) `)
)[1]
const parsePageFirstLoad = (page) =>
stdout.match(
new RegExp(
` ${page} .*?(?:(?:\\d|\\.){1,}) .*? ((?:\\d|\\.){1,} (?:\\w{1,}))`
)
)[1]
const parseSharedSize = (sharedPartName) => {
const matches = stdout.match(
new RegExp(`${sharedPartName} .*? ((?:\\d|\\.){1,} (?:\\w{1,}))`)
)
if (!matches) {
throw new Error(`Could not match ${sharedPartName}`)
}
return matches[1]
}
const indexSize = parsePageSize('/')
const indexFirstLoad = parsePageFirstLoad('/')
const err404Size = parsePageSize('/404')
const err404FirstLoad = parsePageFirstLoad('/404')
const sharedByAll = parseSharedSize('shared by all')
const _appSize = parseSharedSize('_app\\..*?\\.js')
const webpackSize = parseSharedSize('webpack\\..*?\\.js')
const mainSize = parseSharedSize('main\\..*?\\.js')
const frameworkSize = parseSharedSize('framework\\..*?\\.js')
for (const size of [
indexSize,
indexFirstLoad,
err404Size,
err404FirstLoad,
sharedByAll,
_appSize,
webpackSize,
mainSize,
frameworkSize,
]) {
expect(parseFloat(size)).toBeGreaterThan(0)
}
const gz = gzipSize !== false
expect(parseFloat(indexSize) / 1000).toBeCloseTo(
gz ? 0.251 : 0.394,
2
)
expect(indexSize.endsWith('B')).toBe(true)
if (!matches) { expect(parseFloat(indexFirstLoad)).toBeCloseTo(gz ? 63.6 : 195, 1)
throw new Error(`Could not match ${sharedPartName}`) expect(indexFirstLoad.endsWith('kB')).toBe(true)
}
return matches[1] expect(parseFloat(err404Size)).toBeCloseTo(gz ? 3.06 : 8.15, 1)
} expect(err404Size.endsWith('kB')).toBe(true)
const indexSize = parsePageSize('/') expect(parseFloat(err404FirstLoad)).toBeCloseTo(gz ? 66.4 : 203, 1)
const indexFirstLoad = parsePageFirstLoad('/') expect(err404FirstLoad.endsWith('kB')).toBe(true)
const err404Size = parsePageSize('/404')
const err404FirstLoad = parsePageFirstLoad('/404')
const sharedByAll = parseSharedSize('shared by all')
const _appSize = parseSharedSize('_app\\..*?\\.js')
const webpackSize = parseSharedSize('webpack\\..*?\\.js')
const mainSize = parseSharedSize('main\\..*?\\.js')
const frameworkSize = parseSharedSize('framework\\..*?\\.js')
for (const size of [
indexSize,
indexFirstLoad,
err404Size,
err404FirstLoad,
sharedByAll,
_appSize,
webpackSize,
mainSize,
frameworkSize,
]) {
expect(parseFloat(size)).toBeGreaterThan(0)
}
// should be no bigger than 291 bytes expect(parseFloat(sharedByAll)).toBeCloseTo(gz ? 63.4 : 195, 1)
expect(parseFloat(indexSize) - 291).toBeLessThanOrEqual(0) expect(sharedByAll.endsWith('kB')).toBe(true)
expect(indexSize.endsWith('B')).toBe(true)
// should be no bigger than 64.8 kb const appSizeValue = _appSize.endsWith('kB')
expect(parseFloat(indexFirstLoad)).toBeCloseTo(63.6, 1) ? parseFloat(_appSize)
expect(indexFirstLoad.endsWith('kB')).toBe(true) : parseFloat(_appSize) / 1000
expect(appSizeValue).toBeCloseTo(gz ? 1.0 : 2.18, 1)
expect(_appSize.endsWith('kB') || _appSize.endsWith(' B')).toBe(true)
expect(parseFloat(err404Size)).toBeCloseTo(3.04, 1) const webpackSizeValue = webpackSize.endsWith('kB')
expect(err404Size.endsWith('kB')).toBe(true) ? parseFloat(webpackSize)
: parseFloat(webpackSize) / 1000
expect(webpackSizeValue).toBeCloseTo(gz ? 0.95 : 1.81, 2)
expect(webpackSize.endsWith('kB') || webpackSize.endsWith(' B')).toBe(
true
)
expect(parseFloat(err404FirstLoad)).toBeCloseTo(66.3, 0) expect(parseFloat(mainSize)).toBeCloseTo(gz ? 19.4 : 60.4, 1)
expect(err404FirstLoad.endsWith('kB')).toBe(true) expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(sharedByAll)).toBeCloseTo(63.4, 1) expect(parseFloat(frameworkSize)).toBeCloseTo(gz ? 42.0 : 130, 1)
expect(sharedByAll.endsWith('kB')).toBe(true) expect(frameworkSize.endsWith('kB')).toBe(true)
})
if (_appSize.endsWith('kB')) { it('should not emit extracted comments', async () => {
expect(parseFloat(_appSize)).toBeLessThanOrEqual(1.02) const files = await recursiveReadDir(
expect(_appSize.endsWith('kB')).toBe(true) join(appDir, '.next'),
} else { /\.txt|\.LICENSE\./
expect(parseFloat(_appSize) - 1000).toBeLessThanOrEqual(0) )
expect(_appSize.endsWith(' B')).toBe(true) expect(files).toEqual([])
})
} }
)
expect(parseFloat(webpackSize) - 952).toBeLessThanOrEqual(0) }
expect(webpackSize.endsWith(' B')).toBe(true)
expect(parseFloat(mainSize) - 19.4).toBeLessThanOrEqual(0)
expect(mainSize.endsWith('kB')).toBe(true)
expect(parseFloat(frameworkSize) - 42.1).toBeLessThanOrEqual(0)
expect(frameworkSize.endsWith('kB')).toBe(true)
})
it('should not emit extracted comments', async () => {
const files = await recursiveReadDir(
join(appDir, '.next'),
/\.txt|\.LICENSE\./
)
expect(files).toEqual([])
})
})
describe('Custom App Output', () => { describe('Custom App Output', () => {
const appDir = join(fixturesDir, 'with-app') const appDir = join(fixturesDir, 'with-app')
......
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