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