Unverified Commit ab9bada7 authored by Steven's avatar Steven Committed by GitHub

chore(export)!: remove `next export` in favor of `output: export` in next.config.js (#57085)

BREAKING CHANGE

Since `next export` has been printing a deprecation warning since https://github.com/vercel/next.js/pull/47376, its safe to remove in semver-major.

The upgrade path is to simply add `output: 'export'` in `next.config.js` - everything will continue to work the same.

This config greatly improves the `next dev` experience today. And in the future, it will improve performance of `next build` because we no longer need to do two passes (build then export).
parent 72085357
......@@ -2149,7 +2149,6 @@ export default async function build(
}
const exportOptions: ExportAppOptions = {
isInvokedFromCli: false,
nextConfig: exportConfig,
hasAppDir,
silent: false,
......@@ -2835,7 +2834,6 @@ export default async function build(
)
const options: ExportAppOptions = {
isInvokedFromCli: false,
buildExport: false,
nextConfig: config,
hasAppDir,
......
#!/usr/bin/env node
import type { ExportAppOptions } from '../export/types'
import { resolve, join } from 'path'
import { existsSync } from 'fs'
import { cyan } from '../lib/picocolors'
import exportApp, { ExportError } from '../export'
import * as Log from '../build/output/log'
import { printAndExit } from '../server/lib/utils'
import type { CliCommand } from '../lib/commands'
import { trace } from '../trace'
import { getProjectDir } from '../lib/get-project-dir'
const nextExport: CliCommand = (args) => {
const nextExportCliSpan = trace('next-export-cli')
if (args['--help']) {
console.log(`
Description
[DEPRECATED] Exports a static version of the application for production deployment
Usage
$ next export [options] <dir>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--outdir, -o Set the output dir (defaults to 'out')
--silent, -s Do not print any messages to console
--threads Max number of threads to use
--help, -h List this help
The "next export" command is deprecated in favor of "output: export" in next.config.js
Learn more: ${cyan(
'https://nextjs.org/docs/advanced-features/static-html-export'
)}
`)
process.exit(0)
}
const dir = getProjectDir(args._[0])
// Check if pages dir exists and warn if not
if (!existsSync(dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
const options: ExportAppOptions = {
silent: args['--silent'] || false,
threads: args['--threads'],
outdir: args['--outdir'] ? resolve(args['--outdir']) : join(dir, 'out'),
hasOutdirFromCli: Boolean(args['--outdir']),
isInvokedFromCli: true,
hasAppDir: false,
buildExport: false,
}
exportApp(dir, options, nextExportCliSpan)
.then(() => {
nextExportCliSpan.stop()
printAndExit(`Export successful. Files written to ${options.outdir}`, 0)
})
.catch((err: any) => {
nextExportCliSpan.stop()
if (err instanceof ExportError || err.code === 'NEXT_EXPORT_ERROR') {
Log.error(err.message)
} else {
console.error(err)
}
process.exit(1)
})
const nextExport: CliCommand = () => {
Log.error(`
The "next export" command has been removed in favor of "output: export" in next.config.js. Learn more: ${cyan(
'https://nextjs.org/docs/advanced-features/static-html-export'
)}
`)
process.exit(1)
}
export { nextExport }
......@@ -222,31 +222,6 @@ export async function exportAppImpl(
.traceAsyncFn(() => loadConfig(PHASE_EXPORT, dir)))
const distDir = join(dir, nextConfig.distDir)
const isExportOutput = nextConfig.output === 'export'
// Running 'next export'
if (options.isInvokedFromCli) {
if (isExportOutput) {
if (options.hasOutdirFromCli) {
throw new ExportError(
'"next export -o <dir>" cannot be used when "output: export" is configured in next.config.js. Instead add "distDir" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
)
}
Log.warn(
'"next export" is no longer needed when "output: export" is configured in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
)
return null
}
if (existsSync(join(distDir, 'server', 'app'))) {
throw new ExportError(
'"next export" does not work with App Router. Please use "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
)
}
Log.warn(
'"next export" is deprecated in favor of "output: export" in next.config.js https://nextjs.org/docs/advanced-features/static-html-export'
)
}
const telemetry = options.buildExport ? null : new Telemetry({ distDir })
if (telemetry) {
......@@ -475,7 +450,7 @@ export async function exportAppImpl(
SERVER_DIRECTORY,
SERVER_REFERENCE_MANIFEST + '.json'
))
if (options.isInvokedFromCli || isExportOutput) {
if (nextConfig.output === 'export') {
if (
Object.keys(serverActionsManifest.node).length > 0 ||
Object.keys(serverActionsManifest.edge).length > 0
......@@ -629,7 +604,7 @@ export async function exportAppImpl(
// Warn if the user defines a path for an API page
if (hasApiRoutes || hasMiddleware) {
if (!options.silent) {
if (nextConfig.output === 'export') {
Log.warn(
yellow(
`Statically exporting a Next.js application via \`next export\` disables API routes and middleware.`
......
......@@ -95,7 +95,6 @@ export type ExportWorker = (
export interface ExportAppOptions {
outdir: string
isInvokedFromCli: boolean
hasAppDir: boolean
silent?: boolean
threads?: number
......
module.exports = {
output: 'export',
// exportPathMap
}
......@@ -2,10 +2,10 @@
import { promises } from 'fs'
import { join } from 'path'
import { validateAMP } from 'amp-test-utils'
import { File, nextBuild, nextExport, runNextCommand } from 'next-test-utils'
import { File, nextBuild, runNextCommand } from 'next-test-utils'
import { existsSync } from 'fs-extra'
const { access, readFile } = promises
const { access } = promises
const appDir = join(__dirname, '../')
const outDir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js'))
......@@ -19,7 +19,6 @@ describe('AMP Validation on Export', () => {
stdout: true,
stderr: true,
})
await nextExport(appDir, { outdir: outDir }, { ignoreFail: true })
buildOutput = stdout + stderr
})
......@@ -27,16 +26,7 @@ describe('AMP Validation on Export', () => {
expect(buildOutput).toMatch(
/error.*The mandatory attribute 'height' is missing in tag 'amp-video'\./
)
})
it('should export AMP pages', async () => {
const toCheck = ['first', 'second', 'third.amp']
await Promise.all(
toCheck.map(async (page) => {
const content = await readFile(join(outDir, `${page}.html`))
await validateAMP(content.toString())
})
)
expect(existsSync(outDir)).toBeFalse()
})
// this is now an error instead of a warning
......
......@@ -7,14 +7,15 @@ import { validateAMP } from 'amp-test-utils'
import {
nextBuild,
renderViaHTTP,
File,
findPort,
launchApp,
killApp,
nextStart,
nextExport,
} from 'next-test-utils'
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
let builtServerPagesDir
let appPort
let app
......@@ -124,11 +125,13 @@ describe('AMP SSG Support', () => {
let buildId
beforeAll(async () => {
nextConfig.write(`module.exports = { output: 'export' }`)
await nextBuild(appDir)
await nextExport(appDir, { outdir: join(appDir, 'out') })
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(() => nextConfig.delete())
it('should have copied SSG files correctly', async () => {
const outFile = (file) => join(appDir, 'out', file)
......
......@@ -8,10 +8,10 @@ import {
findPort,
launchApp,
fetchViaHTTP,
File,
renderViaHTTP,
nextBuild,
nextStart,
nextExport,
getPageFileFromBuildManifest,
getPageFileFromPagesManifest,
check,
......@@ -593,15 +593,16 @@ function runTests(dev = false) {
expect(await req.text()).toBe('hello world')
})
} else {
it('should show warning with next export', async () => {
const { stderr } = await nextExport(
appDir,
{ outdir: join(appDir, 'out') },
{ stderr: true }
)
expect(stderr).toContain(
'https://nextjs.org/docs/messages/api-routes-static-export'
)
it('should show error with output export', async () => {
const nextConfig = new File(join(appDir, 'next.config.js'))
nextConfig.write(`module.exports = { output: 'export' }`)
try {
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toContain('https://nextjs.org/docs/messages/gssp-export')
expect(code).toBe(1)
} finally {
nextConfig.delete()
}
})
it('should build api routes', async () => {
......
import fs from 'fs-extra'
import { nextBuild, nextExport, nextExportDefault } from 'next-test-utils'
import { nextBuild, runNextCommand } from 'next-test-utils'
import { join } from 'path'
import {
appDir,
......@@ -33,61 +33,10 @@ describe('app dir - with output export (next dev / next build)', () => {
'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.'
)
})
it('should warn about "next export" is no longer needed with config', async () => {
it('should error when running next export', async () => {
await fs.remove(distDir)
await fs.remove(exportDir)
await nextBuild(appDir)
expect(await getFiles()).toEqual(expectedWhenTrailingSlashTrue)
let stdout = ''
let stderr = ''
await nextExportDefault(appDir, {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
expect(stderr).toContain(
'"next export" is no longer needed when "output: export" is configured in next.config.js'
)
expect(stdout).toContain('Export successful. Files written to')
expect(await getFiles()).toEqual(expectedWhenTrailingSlashTrue)
})
it('should error when "next export -o <dir>" is used with config', async () => {
await fs.remove(distDir)
await fs.remove(exportDir)
await nextBuild(appDir)
expect(await getFiles()).toEqual(expectedWhenTrailingSlashTrue)
let stdout = ''
let stderr = ''
let error = undefined
try {
await nextExport(
appDir,
{ outdir: exportDir },
{
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
}
)
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(stderr).toContain(
'"next export -o <dir>" cannot be used when "output: export" is configured in next.config.js. Instead add "distDir" in next.config.js'
)
expect(stdout).not.toContain('Export successful. Files written to')
})
it('should error when no config.output detected for next export', async () => {
await fs.remove(distDir)
await fs.remove(exportDir)
nextConfig.replace(`output: 'export',`, '')
nextConfig.delete()
try {
await nextBuild(appDir)
expect(await getFiles()).toEqual([])
......@@ -95,24 +44,20 @@ describe('app dir - with output export (next dev / next build)', () => {
let stderr = ''
let error = undefined
try {
await nextExport(
appDir,
{ outdir: exportDir },
{
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
}
)
await runNextCommand(['export', appDir], {
onStdout(msg) {
stdout += msg
},
onStderr(msg) {
stderr += msg
},
})
} catch (e) {
error = e
}
expect(error).toBeDefined()
expect(stderr).toContain(
'"next export" does not work with App Router. Please use "output: export" in next.config.js'
'The "next export" command has been removed in favor of "output: export" in next.config.js'
)
expect(stdout).not.toContain('Export successful. Files written to')
expect(await getFiles()).toEqual([])
......
module.exports = {
output: 'export',
exportPathMap() {
return {
'/': { page: '/hello', query: { first: 'second' } },
......
/* eslint-env jest */
import path from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = path.join(__dirname, '..')
const outdir = path.join(__dirname, 'out')
let stderr
let exitCode
......@@ -24,12 +23,9 @@ const runTests = () => {
describe('Auto Export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
const { stderr: curStderr, code: curCode } = await nextExport(
appDir,
{ outdir },
{ stderr: true }
)
const { stderr: curStderr, code: curCode } = await nextBuild(appDir, [], {
stderr: true,
})
stderr = curStderr
exitCode = curCode
})
......
......@@ -359,7 +359,6 @@ describe('CLI Usage', () => {
['buidl', 'build'],
['buill', 'build'],
['biild', 'build'],
['exporr', 'export'],
['starr', 'start'],
['dee', 'dev'],
]
......@@ -756,37 +755,12 @@ describe('CLI Usage', () => {
test('--help', async () => {
const help = await runNextCommand(['export', '--help'], {
stdout: true,
})
expect(help.stdout).toMatch(/Exports a static version of the application/)
})
test('-h', async () => {
const help = await runNextCommand(['export', '-h'], {
stdout: true,
})
expect(help.stdout).toMatch(/Exports a static version of the application/)
})
test('should warn when unknown argument provided', async () => {
const { stderr } = await runNextCommand(['export', '--random'], {
stderr: true,
})
expect(stderr).toEqual('Unknown or unexpected option: --random\n')
})
test('should not throw UnhandledPromiseRejectionWarning', async () => {
const { stderr } = await runNextCommand(['export', '--random'], {
stderr: true,
})
expect(stderr).not.toContain('UnhandledPromiseRejectionWarning')
})
test('invalid directory', async () => {
const output = await runNextCommand(['export', 'non-existent'], {
stderr: true,
})
expect(output.stderr).toContain(
'Invalid project directory provided, no such directory'
expect(help.stderr).toMatch(
'The "next export" command has been removed in favor of "output: export" in next.config.js'
)
expect(help.code).toBe(1)
})
})
......
module.exports = {
// REPLACEME
experimental: {
caseSensitiveRoutes: true,
},
......
......@@ -16,16 +16,17 @@ import {
nextBuild,
nextStart,
fetchViaHTTP,
File,
renderViaHTTP,
getBrowserBodyText,
waitFor,
normalizeRegEx,
nextExport,
hasRedbox,
check,
} from 'next-test-utils'
let appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
const nextConfigPath = join(appDir, 'next.config.js')
let externalServerHits = new Set()
let nextConfigRestoreContent
......@@ -2707,71 +2708,6 @@ describe('Custom routes', () => {
`rewrites, redirects, and headers are not applied when exporting your application detected`
)
})
it('should not show warning for experimental has usage', async () => {
expect(stderr).not.toContain(
"'has' route field support is still experimental and not covered by semver, use at your own risk."
)
})
})
describe('export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)(
'production mode',
() => {
let exportStderr = ''
let exportVercelStderr = ''
beforeAll(async () => {
const { stdout: buildStdout, stderr: buildStderr } = await nextBuild(
appDir,
['-d'],
{
stdout: true,
stderr: true,
}
)
const exportResult = await nextExport(
appDir,
{ outdir: join(appDir, 'out') },
{ stderr: true }
)
const exportVercelResult = await nextExport(
appDir,
{ outdir: join(appDir, 'out') },
{
stderr: true,
env: {
NOW_BUILDER: '1',
},
}
)
stdout = buildStdout
stderr = buildStderr
exportStderr = exportResult.stderr
exportVercelStderr = exportVercelResult.stderr
})
it('should not show warning for custom routes when not next export', async () => {
expect(stderr).not.toContain(
`rewrites, redirects, and headers are not applied when exporting your application detected`
)
})
it('should not show warning for custom routes when next export on Vercel', async () => {
expect(exportVercelStderr).not.toContain(
`rewrites, redirects, and headers are not applied when exporting your application detected`
)
})
it('should show warning for custom routes with next export', async () => {
expect(exportStderr).toContain(
`rewrites, redirects, and headers are not applied when exporting your application, detected (rewrites, redirects, headers)`
)
})
}
)
})
describe('should load custom routes when only one type is used', () => {
......@@ -2880,3 +2816,29 @@ describe('Custom routes', () => {
)
})
})
describe('export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
beforeAll(async () => {
nextConfig.replace('// REPLACEME', `output: 'export',`)
const { stdout: buildStdout, stderr: buildStderr } = await nextBuild(
appDir,
['-d'],
{
stdout: true,
stderr: true,
}
)
stdout = buildStdout
stderr = buildStderr
})
afterAll(() => nextConfig.restore())
it('should not show warning for custom routes when not next export', async () => {
expect(stderr).not.toContain(
`rewrites, redirects, and headers are not applied when exporting your application detected`
)
})
})
})
......@@ -2,12 +2,15 @@
import path from 'path'
import fs from 'fs-extra'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = path.join(__dirname, '..')
const nextConfig = path.join(appDir, 'next.config.js')
describe('Errors on output to public', () => {
afterEach(async () => {
await fs.remove(nextConfig)
})
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('Throws error when `distDir` is set to public', async () => {
await fs.writeFile(nextConfig, `module.exports = { distDir: 'public' }`)
......@@ -18,23 +21,19 @@ describe('Errors on output to public', () => {
expect(results.stdout + results.stderr).toMatch(
/The 'public' directory is reserved in Next\.js and can not be set as/
)
await fs.remove(nextConfig)
})
it('Throws error when export out dir is public', async () => {
await fs.remove(nextConfig)
await nextBuild(appDir)
const outdir = path.join(appDir, 'public')
const results = await nextExport(
appDir,
{ outdir },
{
stdout: true,
stderr: true,
}
await fs.writeFile(
nextConfig,
`module.exports = { distDir: 'public', output: 'export' }`
)
const results = await nextBuild(appDir, [], {
stdout: true,
stderr: true,
})
expect(results.stdout + results.stderr).toMatch(
/The 'public' directory is reserved in Next\.js and can not be used as/
/The 'public' directory is reserved in Next\.js and can not be/
)
})
})
......
module.exports = {
output: 'export',
distDir: 'static',
}
/* eslint-env jest */
import path from 'path'
import fs from 'fs-extra'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = path.join(__dirname, '..')
const nextConfig = path.join(appDir, 'next.config.js')
describe('Errors on output to static', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('Throws error when export out dir is static', async () => {
await fs.remove(nextConfig)
await nextBuild(appDir)
const outdir = path.join(appDir, 'static')
const results = await nextExport(
appDir,
{ outdir },
{
stdout: true,
stderr: true,
}
)
const results = await nextBuild(appDir, [], {
stdout: true,
stderr: true,
})
expect(results.stdout + results.stderr).toMatch(
/The 'static' directory is reserved in Next\.js and can not be used as/
)
......
module.exports = (phase) => {
return {
output: 'export',
trailingSlash: false,
}
}
......@@ -2,7 +2,7 @@
import { promises } from 'fs'
import { join } from 'path'
import { nextBuild, nextExport, File } from 'next-test-utils'
import { nextBuild, File } from 'next-test-utils'
const { readFile, access, stat } = promises
const appDir = join(__dirname, '../')
......@@ -22,7 +22,6 @@ describe('Static 404 Export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('only export 404.html when trailingSlash: false', async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
expect(await fileExist(join(outdir, '404.html'))).toBe(true)
expect(await fileExist(join(outdir, '404.html.html'))).toBe(false)
......@@ -32,7 +31,6 @@ describe('Static 404 Export', () => {
it('export 404.html and 404/index.html when trailingSlash: true', async () => {
nextConfig.replace(`trailingSlash: false`, `trailingSlash: true`)
await nextBuild(appDir)
await nextExport(appDir, { outdir })
nextConfig.restore()
expect(await fileExist(join(outdir, '404/index.html'))).toBe(true)
......@@ -46,7 +44,6 @@ describe('Export with a page named 404.js', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('should export a custom 404.html instead of default 404.html', async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
const html = await readFile(join(outdir, '404.html'), 'utf8')
expect(html).toMatch(/this is a 404 page override the default 404\.html/)
......
module.exports = {
output: 'export',
}
......@@ -3,7 +3,7 @@
import { promises } from 'fs'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const { access, readFile } = promises
const appDir = join(__dirname, '../')
......@@ -13,7 +13,6 @@ describe('Export with default map', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
})
it('should export with folder that has dot in name', async () => {
......
module.exports = {
output: 'export',
exportPathMap() {
return {
'/regression/jeff-is-cool': { page: '/regression/[slug]' },
......
......@@ -5,7 +5,6 @@ import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
import {
nextBuild,
nextExport,
startCleanStaticServer,
stopApp,
renderViaHTTP,
......@@ -20,7 +19,6 @@ describe('Export Dynamic Pages', () => {
let port
beforeAll(async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
server = await startCleanStaticServer(outdir)
port = server.address().port
......
module.exports = {
output: 'export',
exportPathMap() {
return {
'/first': { page: '/[slug]' },
......
......@@ -2,26 +2,25 @@
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export error for fallback: true', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
const { code, stderr } = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
it('should have error during next export', async () => {
const { stderr } = await nextExport(appDir, { outdir }, { stderr: true })
expect(stderr).toContain('Found pages with `fallback` enabled')
expect(stderr).toContain(
'Pages with `fallback` enabled in `getStaticPaths` can not be exported'
)
expect(stderr).toContain('/[slug]')
expect(code).toBe(1)
})
})
})
module.exports = {
output: 'export',
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
......
/* eslint-env jest */
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export with getInitialProps', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('should show warning with next export', async () => {
await nextBuild(appDir)
const { stderr } = await nextExport(appDir, { outdir }, { stderr: true })
const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toContain(
'https://nextjs.org/docs/messages/get-initial-props-export'
)
......
module.exports = {
output: 'export',
}
......@@ -2,24 +2,20 @@
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export with default loader next/image component', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('should build successfully', async () => {
it('should error during next build', async () => {
await fs.remove(join(appDir, '.next'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should have error during next export', async () => {
const { stderr } = await nextExport(appDir, { outdir }, { stderr: true })
await fs.remove(join(appDir, 'out'))
const { code, stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toContain(
'Image Optimization using the default loader is not compatible with export.'
)
expect(code).toBe(1)
})
})
})
......@@ -3,7 +3,7 @@
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport, File } from 'next-test-utils'
import { nextBuild, File } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
......@@ -16,6 +16,7 @@ describe('Export with cloudinary loader next/legacy/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'cloudinary',
path: 'https://example.com/',
......@@ -25,13 +26,9 @@ describe('Export with cloudinary loader next/legacy/image component', () => {
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(outdir)
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
expect(code).toBe(0)
})
it('should contain img element in html output', async () => {
......@@ -52,6 +49,7 @@ describe('Export with custom loader next/legacy/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'custom',
},
......@@ -64,13 +62,9 @@ describe('Export with custom loader next/legacy/image component', () => {
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(outdir)
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
expect(code).toBe(0)
})
it('should contain img element with same src in html output', async () => {
......@@ -92,6 +86,7 @@ describe('Export with custom loader config but no loader prop on next/legacy/ima
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'custom',
},
......@@ -100,6 +95,7 @@ describe('Export with custom loader config but no loader prop on next/legacy/ima
})
it('should fail build', async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(outdir)
const { code, stderr } = await nextBuild(appDir, [], { stderr: true })
expect(code).toBe(1)
expect(stderr).toContain(
......@@ -120,6 +116,7 @@ describe('Export with unoptimized next/legacy/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
unoptimized: true,
},
......@@ -128,13 +125,9 @@ describe('Export with unoptimized next/legacy/image component', () => {
})
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(outdir)
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
expect(code).toBe(0)
})
it('should contain img element with same src in html output', async () => {
......
......@@ -3,7 +3,7 @@
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport, File } from 'next-test-utils'
import { nextBuild, File } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
......@@ -16,6 +16,7 @@ describe('Export with cloudinary loader next/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'cloudinary',
path: 'https://example.com/',
......@@ -29,11 +30,6 @@ describe('Export with cloudinary loader next/image component', () => {
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
......@@ -52,6 +48,7 @@ describe('Export with custom loader next/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'custom',
},
......@@ -68,11 +65,6 @@ describe('Export with custom loader next/image component', () => {
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
......@@ -92,6 +84,7 @@ describe('Export with custom loader config but no loader prop on next/image', ()
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'custom',
},
......@@ -120,6 +113,7 @@ describe('Export with loaderFile config next/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
loader: 'custom',
loaderFile: './dummy-loader.js',
......@@ -133,11 +127,6 @@ describe('Export with loaderFile config next/image component', () => {
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
......@@ -157,6 +146,7 @@ describe('Export with unoptimized next/image component', () => {
await nextConfig.replace(
'{ /* replaceme */ }',
JSON.stringify({
output: 'export',
images: {
unoptimized: true,
},
......@@ -169,11 +159,6 @@ describe('Export with unoptimized next/image component', () => {
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
})
it('should contain img element with same src in html output', async () => {
const html = await fs.readFile(join(outdir, 'index.html'))
const $ = cheerio.load(html)
......
......@@ -2,22 +2,17 @@
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
describe('Export index page with `notFound: true` in `getStaticProps`', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
it('should build successfully', async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(join(appDir, 'out'))
const { code } = await nextBuild(appDir)
if (code !== 0) throw new Error(`build failed with status ${code}`)
})
it('should export successfully', async () => {
const { code } = await nextExport(appDir, { outdir })
if (code !== 0) throw new Error(`export failed with status ${code}`)
expect(code).toBe(0)
})
})
})
module.exports = {
output: 'export',
exportPathMap() {
return { '/': { page: '/' } }
},
......
module.exports = {
output: 'export',
distDir: 'lel',
exportTrailingSlash: true,
}
/* eslint-env jest */
import { remove } from 'fs-extra'
import { nextBuild, nextExport, nextExportDefault } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
import path, { join } from 'path'
import fs from 'fs'
......@@ -12,14 +12,15 @@ describe('Application Export Intent Output', () => {
describe('Default Export', () => {
const appDir = join(fixturesDir, 'default-export')
const distDir = join(appDir, '.next')
const outDir = join(appDir, 'out')
beforeAll(async () => {
await remove(distDir)
await remove(outDir)
})
it('should build and export', async () => {
await nextBuild(appDir)
await nextExportDefault(appDir)
})
it('should have the expected outputs for export', () => {
......@@ -59,14 +60,15 @@ describe('Application Export Intent Output', () => {
() => {
const appDir = join(fixturesDir, 'custom-export')
const distDir = join(appDir, '.next')
const outDir = join(appDir, 'out')
beforeAll(async () => {
await remove(distDir)
await remove(outDir)
})
it('should build and export', async () => {
await nextBuild(appDir)
await nextExportDefault(appDir)
})
it('should have the expected outputs for export', () => {
......@@ -107,14 +109,15 @@ describe('Application Export Intent Output', () => {
() => {
const appDir = join(fixturesDir, 'custom-out')
const distDir = join(appDir, '.next')
const outDir = join(appDir, 'lel')
beforeAll(async () => {
await remove(distDir)
await remove(outDir)
})
it('should build and export', async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir: join(appDir, 'lel') })
})
it('should have the expected outputs for export', () => {
......@@ -155,14 +158,17 @@ describe('Application Export Intent Output', () => {
() => {
const appDir = join(fixturesDir, 'bad-export')
const distDir = join(appDir, '.next')
const outDir = join(appDir, 'out')
beforeAll(async () => {
await remove(distDir)
await remove(outDir)
})
it('should build and export', async () => {
await nextBuild(appDir)
await nextExportDefault(appDir, { ignoreFail: true })
const result = await nextBuild(appDir, [], { stderr: true })
expect(result.stderr).toMatch('A.getInitialProps()')
expect(result.code).toBe(1)
})
it('should have the expected outputs for export', () => {
......@@ -231,14 +237,6 @@ describe('Application Export Intent Output', () => {
}).toThrowError(/ENOENT/)
})
it('should export and create file', async () => {
await nextExportDefault(appDir)
expect(() => {
fs.readFileSync(join(distDir, 'export-detail.json'), 'utf8')
}).not.toThrow()
})
it('should build and clean up', async () => {
await nextBuild(appDir)
......
module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60,
},
rewrites() {
// add a rewrite so the code isn't dead-code eliminated
return [
{
source: '/some-rewrite',
destination: '/',
},
]
},
redirects() {
return [
{
source: '/redirect/me/to-about/:lang',
destination: '/:lang/about',
permanent: false,
},
{
source: '/nonexistent',
destination: '/about',
permanent: false,
},
{
source: '/shadowed-page',
destination: '/about',
permanent: false,
},
{
source: '/redirect-query-test/:path',
destination: '/about?foo=:path',
permanent: false,
},
]
},
}
/* eslint-env jest */
import { nextExport } from 'next-test-utils'
import { join } from 'path'
const appDir = join(__dirname, '../')
describe('next export without build', () => {
it('should show error when there is no production build', async () => {
const result = await nextExport(appDir, {}, { stderr: true, stdout: true })
console.log(result.stdout, result.stderr)
expect(result.stderr).toMatch(/Could not find a production build in the/)
})
})
/* eslint-env jest */
import { join } from 'path'
import { nextBuild, nextExportDefault } from 'next-test-utils'
const appDir = join(__dirname, '../')
describe('Export cli prints progress info', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
let buildStdout
let exportStdout
beforeAll(async () => {
const buildResult = await nextBuild(appDir, [], { stdout: true })
buildStdout = buildResult.stdout
const exportResult = await nextExportDefault(appDir, { stdout: true })
exportStdout = exportResult.stdout
})
it('build: should log with internally passed statusMessage', async () => {
const lines = buildStdout.split('\n')
// Search `info - Generating static pages (n/m)` line
const found = lines.some((line) =>
/Generating static pages \(\d+\/\d+\)/.test(line)
)
expect(found).toBeTruthy()
})
it('export: should log with default label', async () => {
const lines = exportStdout.split('\n')
// Search `info - Exporting (n/m)` line
const found = lines.some((line) => /Exporting \(\d+\/\d+\)/.test(line))
expect(found).toBeTruthy()
})
})
})
module.exports = {
output: 'export',
}
/* eslint-env jest */
import { promises } from 'fs'
import { access, readFile } from 'fs/promises'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const { access, readFile } = promises
const appDir = join(__dirname, '../')
const outdir = join(appDir, 'out')
......@@ -13,7 +12,6 @@ describe('Export config#exportTrailingSlash set to false', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
await nextExport(appDir, { outdir })
})
it('should export pages as [filename].html instead of [filename]/index.html', async () => {
......
/* eslint-env jest */
import fs from 'fs-extra'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
import { join } from 'path'
const appDir = join(__dirname, '..')
const nextConfig = join(appDir, 'next.config.js')
const runTests = () => {
it('should build successfully', async () => {
const { stdout, code } = await nextBuild(appDir, [], { stdout: true })
expect(code).toBe(0)
expect(stdout).toMatch(/Compiled successfully/)
})
it('should show error for GSSP during export', async () => {
const { stderr, code } = await nextExport(
appDir,
{ outdir: join(appDir, 'out') },
{ stderr: true }
)
const { stderr, code } = await nextBuild(appDir, [], { stderr: true })
expect(code).toBe(1)
expect(stderr).toMatch(
......@@ -30,9 +19,9 @@ const runTests = () => {
describe('getServerSideProps', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
beforeAll(async () => {
await fs.remove(nextConfig)
afterAll(async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(join(appDir, 'out'))
})
runTests()
......
......@@ -4,17 +4,18 @@ import fs from 'fs-extra'
import { join } from 'path'
import {
fetchViaHTTP,
File,
findPort,
launchApp,
killApp,
nextBuild,
nextStart,
nextExport,
} from 'next-test-utils'
let app
let appPort
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
const srcHeader = 'X-From-Src-Middleware'
const rootHeader = 'X-From-Root-Middleware'
const rootMiddlewareJSFile = join(appDir, 'middleware.js')
......@@ -103,32 +104,26 @@ describe.each([
let exportOutput = ''
beforeAll(async () => {
await nextBuild(appDir)
nextConfig.write(`module.exports = { output: 'export' }`)
const result = await nextBuild(appDir, [], {
stderr: true,
stdout: true,
})
const outdir = join(__dirname, '..', 'out')
await fs.remove(outdir).catch(() => {})
const result = await nextExport(
appDir,
{ outdir },
{
stderr: true,
stdout: true,
}
)
exportOutput = result.stderr + result.stdout
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
afterAll(() => nextConfig.delete())
it('should warn about middleware on export', async () => {
expect(exportOutput).toContain(
'Statically exporting a Next.js application via `next export` disables API routes and middleware.'
)
})
runTest()
})
})
......@@ -3,7 +3,7 @@
import path from 'path'
import fs from 'fs-extra'
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const appDir = join(__dirname, '../')
const nextConfig = join(appDir, 'next.config.js')
......@@ -82,6 +82,7 @@ describe('no-op export', () => {
nextConfig,
`
module.exports = {
output: 'export',
exportPathMap() {
return {}
}
......@@ -93,11 +94,6 @@ describe('no-op export', () => {
stdout: 'log',
})
expect(buildResult.code).toBe(0)
const exportResult = await nextExport(appDir, {
outdir: join(appDir, 'out'),
})
expect(exportResult.code).toBe(0)
})
})
})
module.exports = {
output: 'export',
exportTrailingSlash: true,
exportPathMap: function (defaultPathMap) {
if (defaultPathMap['/blog/[post]']) {
throw new Error('Found Incremental page in the default export path map')
}
return defaultPathMap
},
}
import Link from 'next/link'
import fs from 'fs'
import path from 'path'
export async function getStaticProps() {
const text = fs
.readFileSync(path.join(process.cwd(), 'world.txt'), 'utf8')
.trim()
return {
props: {
world: text,
time: new Date().getTime(),
},
}
}
export default ({ world, time }) => (
<>
<p>hello {world}</p>
<span id="anotherTime">time: {time}</span>
<Link href="/" id="home">
to home
</Link>
<br />
<Link href="/something" id="something">
to something
</Link>
</>
)
import { useRouter } from 'next/router'
export const getStaticProps = () => {
return {
props: {
hello: 'world',
},
}
}
export const getStaticPaths = () => {
return {
paths: ['/api-docs/first'],
fallback: false,
}
}
export default function Slug(props) {
if (useRouter().isFallback) return 'Loading...'
return (
<>
<p id="api-docs">API Docs</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
export default function handler(req, res) {
throw new Error('lol')
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [{ params: { slug: 'a' } }, { params: { slug: 'b' } }],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1/comment-1',
{ params: { post: 'post-2', comment: 'comment-2' } },
],
fallback: false,
}
}
export async function getStaticProps({ params }) {
return {
props: {
post: params.post,
comment: params.comment,
time: new Date().getTime(),
},
}
}
export default ({ post, comment, time }) => {
// we're in a loading state
if (!post) {
return <p>loading...</p>
}
return (
<>
<p>Post: {post}</p>
<p>Comment: {comment}</p>
<span>time: {time}</span>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import 'firebase/firestore'
export async function getStaticPaths() {
return {
paths: [
'/blog/post-1',
{ params: { post: 'post-2' } },
'/blog/[post3]',
'/blog/post-4',
'/blog/post.1',
'/blog/post.1', // handle duplicates
],
fallback: false,
}
}
let counter = 0
export async function getStaticProps({ params }) {
if (params.post === 'post-10') {
await new Promise((resolve) => {
setTimeout(() => resolve(), 1000)
})
}
if (params.post === 'post-100') {
throw new Error('such broken..')
}
if (params.post === 'post-999') {
if (++counter < 6) {
throw new Error('try again..')
}
}
return {
props: {
params,
post: params.post,
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticProps() {
return {
props: {
slugs: ['post-1', 'post-2'],
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ slugs, time }) => {
return (
<>
<p>Posts: {JSON.stringify(slugs)}</p>
<span>time: {time}</span>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise((resolve) => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
}
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/catchall-explicit/second',
{ params: { slug: ['another', 'value'] } },
'/catchall-explicit/hello/another',
'/catchall-explicit/[first]/[second]',
{ params: { slug: ['[third]', '[fourth]'] } },
],
fallback: false,
}
}
export default function Page({ slug }) {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Hi {slug.join(' ')}</p>{' '}
<Link href="/" id="home">
to home
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
return {
props: {
slug: slug || [],
},
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: [] } }, { params: { slug: ['value'] } }],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="catchall">Catch all: [{slug.join(', ')}]</p>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import { useRouter } from 'next/router'
export async function getStaticProps({ params: { slug } }) {
if (slug[0] === 'delayby3s') {
await new Promise((resolve) => setTimeout(resolve, 3000))
}
return {
props: {
slug,
},
}
}
export async function getStaticPaths() {
return {
paths: [
{ params: { slug: ['first'] } },
'/catchall/second',
{ params: { slug: ['another', 'value'] } },
'/catchall/hello/another',
],
fallback: false,
}
}
export default ({ slug }) => {
const { isFallback } = useRouter()
if (isFallback) {
return <p id="catchall">fallback</p>
}
return <p id="catchall">Hi {slug.join(' ')}</p>
}
import Link from 'next/link'
export async function getStaticProps() {
return {
props: {
world: 'world',
time: new Date().getTime(),
},
}
}
export default ({ world, time }) => (
<>
<p>hello {world}</p>
<span>time: {time}</span>
<Link href="/" id="home">
to home
</Link>
<br />
<Link href="/something" id="something">
to something
</Link>
</>
)
import Link from 'next/link'
export async function getStaticProps({ params: { slug } }) {
return {
props: { slug },
}
}
export async function getStaticPaths() {
return {
paths: [{ params: { slug: '[first]' } }, '/dynamic/[second]'],
fallback: false,
}
}
export default ({ slug }) => {
// Important to not check for `slug` existence (testing that build does not
// render fallback version and error)
return (
<>
<p id="param">Hi {slug}!</p>{' '}
<Link href="/" id="home">
to home
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticPaths() {
return {
paths: [],
fallback: false,
}
}
export async function getStaticProps({ params }) {
await new Promise((resolve) => setTimeout(resolve, 1000))
return {
props: {
params,
hello: 'world',
post: params.slug,
random: Math.random(),
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ post, time, params }) => {
if (useRouter().isFallback) {
return <p>hi fallback</p>
}
return (
<>
<p>Post: {post}</p>
<span>time: {time}</span>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
</>
)
}
import Link from 'next/link'
export async function getStaticProps() {
// throw new Error('oops from getStaticProps')
return {
props: { world: 'world', time: new Date().getTime() },
}
}
const Page = ({ world, time }) => {
return (
<>
{/* <div id='after-change'>idk</div> */}
<p>hello {world}</p>
<span>time: {time}</span>
<Link href="/non-json/[p]" as="/non-json/1" id="non-json">
to non-json
</Link>
<br />
<Link href="/another?hello=world" as="/another/?hello=world" id="another">
to another
</Link>
<br />
<Link href="/something" id="something">
to something
</Link>
<br />
<Link href="/normal" id="normal">
to normal
</Link>
<br />
<Link href="/blog/[post]" as="/blog/post-1" id="post-1">
to dynamic
</Link>
<Link href="/blog/[post]" as="/blog/post-100" id="broken-post">
to broken
</Link>
<Link
href="/blog/[post]"
as="/blog/post-999"
prefetch={false}
id="broken-at-first-post"
>
to broken at first
</Link>
<br />
<Link
href="/blog/[post]/[comment]"
as="/blog/post-1/comment-1"
id="comment-1"
>
to another dynamic
</Link>
<Link href="/catchall/[...slug]" as="/catchall/first" id="to-catchall">
to catchall
</Link>
<br />
<Link href="/index" id="to-nested-index">
to nested index
</Link>
<br />
<Link href="/lang/[lang]/about?lang=en" as="/about" id="to-rewritten-ssg">
to rewritten static path page
</Link>
<br />
<Link
href="/catchall-optional/[[...slug]]"
as="/catchall-optional"
id="catchall-optional-root"
>
to optional catchall root
</Link>
<Link
href="/catchall-optional/[[...slug]]"
as="/catchall-optional/value"
id="catchall-optional-value"
>
to optional catchall page /value
</Link>
<br />
<Link href="/dynamic/[slug]" as="/dynamic/[first]" id="dynamic-first">
to dynamic [first] page
</Link>
<Link href="/dynamic/[slug]" as="/dynamic/[second]" id="dynamic-second">
to dynamic [second] page
</Link>
<br />
<Link
href="/catchall-explicit/[...slug]"
as="/catchall-explicit/[first]/[second]"
id="catchall-explicit-string"
>
to catchall-explicit [first]/[second] page
</Link>
<Link
href="/catchall-explicit/[...slug]"
as="/catchall-explicit/[third]/[fourth]"
id="catchall-explicit-object"
>
to catchall-explicit [third]/[fourth] page
</Link>
</>
)
}
export default Page
import Link from 'next/link'
export async function getStaticProps() {
return {
props: { world: 'nested index' },
}
}
export default ({ world }) => {
return (
<>
<p>hello {world}</p>
<Link href="/" id="home">
to home
</Link>
</>
)
}
export default ({ lang }) => <p id="about">About: {lang}</p>
export const getStaticProps = ({ params: { lang } }) => ({
props: {
lang,
},
})
export const getStaticPaths = () => ({
paths: ['en', 'es', 'fr', 'de'].map((p) => `/lang/${p}/about`),
fallback: false,
})
import { useRouter } from 'next/router'
export async function getStaticProps() {
return {
props: { time: new Date() },
}
}
export async function getStaticPaths() {
return { paths: [], fallback: false }
}
const Page = ({ time }) => {
const { isFallback } = useRouter()
if (isFallback) return null
return <p>hello blocking {time.toString()}</p>
}
export default Page
import { useRouter } from 'next/router'
export async function getStaticProps() {
return {
props: { time: new Date() },
}
}
export async function getStaticPaths() {
return { paths: [], fallback: false }
}
const Page = ({ time }) => {
const { isFallback } = useRouter()
if (isFallback) return null
return <p>hello {time.toString()}</p>
}
export default Page
export default () => <p id="normal-text">a normal page</p>
import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getStaticProps({ params }) {
return {
props: {
world: 'world',
params: params || {},
time: new Date().getTime(),
random: Math.random(),
},
}
}
export default ({ world, time, params, random }) => {
return (
<>
<p>hello: {world}</p>
<span>time: {time}</span>
<div id="random">{random}</div>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/" id="home">
to home
</Link>
<br />
<Link href="/another" id="another">
to another
</Link>
</>
)
}
import React from 'react'
import Link from 'next/link'
export async function getStaticPaths() {
return { paths: [], fallback: false }
}
export async function getStaticProps({ params }) {
return {
props: {
user: params.user,
time: (await import('perf_hooks')).performance.now(),
},
}
}
export default ({ user, time }) => {
return (
<>
<p>User: {user}</p>
<span>time: {time}</span>
<Link href="/" id="home">
to home
</Link>
</>
)
}
/* eslint-env jest */
import fs from 'fs-extra'
import { join } from 'path'
import webdriver from 'next-webdriver'
import {
nextBuild,
renderViaHTTP,
startStaticServer,
stopApp,
waitFor,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
let exportDir = join(appDir, 'out')
let app
let appPort
let buildId
const navigateTest = (dev = false) => {
it('should navigate between pages successfully', async () => {
const toBuild = [
'/',
'/another',
'/something',
'/normal',
'/blog/post-1',
'/blog/post-1/comment-1',
'/catchall/first',
]
await waitFor(2500)
await Promise.all(toBuild.map((pg) => renderViaHTTP(appPort, pg)))
const browser = await webdriver(appPort, '/')
let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
// go to /another
async function goFromHomeToAnother() {
await browser.eval('window.beforeAnother = true')
await browser.elementByCss('#another').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(await browser.eval('window.beforeAnother')).toBe(true)
expect(text).toMatch(/hello.*?world/)
}
await goFromHomeToAnother()
// go to /
async function goFromAnotherToHome() {
await browser.eval('window.didTransition = 1')
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#another')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
}
await goFromAnotherToHome()
// Client-side SSG data caching test
// eslint-disable-next-line no-lone-blocks
{
// Let revalidation period lapse
await waitFor(2000)
// Trigger revalidation (visit page)
await goFromHomeToAnother()
const snapTime = await browser.elementByCss('#anotherTime').text()
// Wait for revalidation to finish
await waitFor(2000)
// Re-visit page
await goFromAnotherToHome()
await goFromHomeToAnother()
const nextTime = await browser.elementByCss('#anotherTime').text()
if (dev) {
expect(snapTime).not.toMatch(nextTime)
} else {
expect(snapTime).toMatch(nextTime)
}
// Reset to Home for next test
await goFromAnotherToHome()
}
// go to /something
await browser.elementByCss('#something').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#post-1')
// go to /blog/post-1
await browser.elementByCss('#post-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Post:.*?post-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /index
await browser.elementByCss('#to-nested-index').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello nested index/)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional
await browser.elementByCss('#catchall-optional-root').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /dynamic/[first]
await browser.elementByCss('#dynamic-first').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#param').text()
expect(text).toMatch(/Hi \[first\]!/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /dynamic/[second]
await browser.elementByCss('#dynamic-second').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#param').text()
expect(text).toMatch(/Hi \[second\]!/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-explicit/[first]/[second]
await browser.elementByCss('#catchall-explicit-string').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi \[first\] \[second\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-explicit/[first]/[second]
await browser.elementByCss('#catchall-explicit-object').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi \[third\] \[fourth\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /catchall-optional/value
await browser.elementByCss('#catchall-optional-value').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p').text()
expect(text).toMatch(/Catch all: \[value\]/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#comment-1')
// go to /blog/post-1/comment-1
await browser.elementByCss('#comment-1').click()
await browser.waitForElementByCss('#home')
text = await browser.elementByCss('p:nth-child(2)').text()
expect(text).toMatch(/Comment:.*?comment-1/)
expect(await browser.eval('window.didTransition')).toBe(1)
// go to /catchall/first
await browser.elementByCss('#home').click()
await browser.waitForElementByCss('#to-catchall')
await browser.elementByCss('#to-catchall').click()
await browser.waitForElementByCss('#catchall')
text = await browser.elementByCss('#catchall').text()
expect(text).toMatch(/Hi.*?first/)
expect(await browser.eval('window.didTransition')).toBe(1)
await browser.close()
})
}
describe('SSG Prerender export', () => {
;(process.env.TURBOPACK ? describe.skip : describe)('production mode', () => {
describe('export mode', () => {
beforeAll(async () => {
await fs.remove(join(appDir, '.next'))
await fs.remove(exportDir)
await nextBuild(appDir, undefined, { cwd: appDir })
app = await startStaticServer(exportDir)
appPort = app.address().port
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
})
afterAll(async () => {
if (app) {
await stopApp(app)
}
})
it('should copy prerender files and honor exportTrailingSlash', async () => {
const routes = [
'/another',
'/something',
'/blog/post-1',
'/blog/post-2/comment-2',
]
for (const route of routes) {
await fs.access(join(exportDir, `${route}/index.html`))
await fs.access(
join(exportDir, '_next/data', buildId, `${route}.json`)
)
}
})
navigateTest()
})
})
})
......@@ -6,11 +6,11 @@ import webdriver from 'next-webdriver'
import escapeRegex from 'escape-string-regexp'
import {
nextBuild,
File,
findPort,
nextStart,
killApp,
waitFor,
nextExport,
stopApp,
startStaticServer,
launchApp,
......@@ -21,6 +21,7 @@ import {
const appDir = join(__dirname, '../app')
const outdir = join(appDir, 'out')
const nextConfig = new File(join(appDir, 'next.config.js'))
let appPort
let app
......@@ -442,11 +443,9 @@ describe('404 handling', () => {
;(process.env.TURBOPACK ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => {
await nextBuild(appDir, [], nextOpts)
})
describe('next start', () => {
beforeAll(async () => {
await nextBuild(appDir, [], nextOpts)
appPort = await findPort()
app = await nextStart(appDir, appPort, nextOpts)
})
......@@ -459,12 +458,14 @@ describe('404 handling', () => {
describe('next export', () => {
beforeAll(async () => {
await nextExport(appDir, { outdir }, nextOpts)
nextConfig.write(`module.exports = { output: 'export' }`)
await nextBuild(appDir, [], nextOpts)
app = await startStaticServer(outdir, join(outdir, '404.html'))
appPort = app.address().port
})
afterAll(() => {
stopApp(app)
afterAll(async () => {
await stopApp(app)
nextConfig.restore()
})
runTests({
......
module.exports = {
output: 'export',
}
// /* eslint-env jest */
import { join } from 'path'
import { nextBuild, nextExport } from 'next-test-utils'
import { nextBuild } from 'next-test-utils'
const nextdir = join(__dirname, '../app')
const outdir = join(nextdir, 'out')
......@@ -17,7 +17,6 @@ if (process.env.TEST_ELECTRON) {
describe('File Protocol via Electron', () => {
beforeAll(async () => {
await nextBuild(nextdir)
await nextExport(nextdir, { outdir })
app = new Application({
path: electron,
......
......@@ -339,11 +339,7 @@ export class NextInstance {
public async build(): Promise<{ exitCode?: number; cliOutput?: string }> {
throw new Error('Not implemented')
}
public async export(args?: {
outdir?: string
}): Promise<{ exitCode?: number; cliOutput?: string }> {
throw new Error('Not implemented')
}
public async setup(parentSpan: Span): Promise<void> {}
public async start(useDirArg: boolean = false): Promise<void> {}
public async stop(): Promise<void> {
......
......@@ -195,35 +195,4 @@ export class NextStartInstance extends NextInstance {
})
})
}
public async export(...[args]: Parameters<NextInstance['export']>) {
return new Promise((resolve) => {
const curOutput = this._cliOutput.length
const exportArgs = ['pnpm', 'next', 'export']
if (args?.outdir) exportArgs.push('--outdir', args.outdir)
if (this.childProcess) {
throw new Error(
`can not run export while server is running, use next.stop() first`
)
}
console.log('running', exportArgs.join(' '))
this.childProcess = spawn(
exportArgs[0],
exportArgs.slice(1),
this.spawnOpts
)
this.handleStdio(this.childProcess)
this.childProcess.on('exit', (code, signal) => {
this.childProcess = undefined
resolve({
exitCode: signal || code,
cliOutput: this.cliOutput.slice(curOutput),
})
})
})
}
}
......@@ -444,14 +444,6 @@ export function nextBuild(
return runNextCommand(['build', dir, ...args], opts)
}
export function nextExport(dir: string, { outdir }, opts: NextOptions = {}) {
return runNextCommand(['export', dir, '--outdir', outdir], opts)
}
export function nextExportDefault(dir: string, opts: NextOptions = {}) {
return runNextCommand(['export', dir], opts)
}
export function nextLint(
dir: string,
args: string[] = [],
......
......@@ -14,6 +14,7 @@ createNextDescribe(
'static export',
{
files: __dirname,
skipStart: true,
},
({ next }) => {
const nextConfigPath = 'next.config.js'
......@@ -25,17 +26,16 @@ createNextDescribe(
let portNoTrailSlash: number
beforeAll(async () => {
await next.stop()
const nextConfig = await next.readFile(nextConfigPath)
await next.export({ outdir })
await next.build()
await next.patchFile(
nextConfigPath,
nextConfig.replace(`trailingSlash: true`, `trailingSlash: false`)
nextConfig
.replace(`trailingSlash: true`, `trailingSlash: false`)
.replace(`distDir: 'out'`, `distDir: '${outNoTrailSlash}'`)
)
await next.build()
await next.export({ outdir: outNoTrailSlash })
await next.patchFile(nextConfigPath, nextConfig)
server = await startStaticServer(path.join(next.testDir, outdir))
......@@ -57,7 +57,13 @@ createNextDescribe(
const tmpOutDir = 'tmpOutDir'
const tempfile = path.join(tmpOutDir, 'temp.txt')
await next.patchFile(tempfile, 'test')
await next.export({ outdir: tmpOutDir })
const nextConfig = await next.readFile(nextConfigPath)
await next.patchFile(
nextConfigPath,
nextConfig.replace(`distDir: 'out'`, `distDir: '${tmpOutDir}'`)
)
await next.build()
await next.patchFile(nextConfigPath, nextConfig)
await expect(next.readFile(tempfile)).rejects.toThrowError()
})
......@@ -100,13 +106,16 @@ createNextDescribe(
describe('Dynamic routes export', () => {
it('Should throw error not matched route', async () => {
const outdir = 'outDynamic'
const nextConfig = await next.readFile(nextConfigPath)
await next.patchFile(
nextConfigPath,
nextConfig.replace('/blog/nextjs/comment/test', '/bad/path')
nextConfig
.replace('/blog/nextjs/comment/test', '/bad/path')
.replace(`distDir: 'out'`, `distDir: '${outdir}'`)
)
const outdir = 'outDynamic'
const { cliOutput } = await next.export({ outdir })
const { cliOutput } = await next.build()
await next.patchFile(nextConfigPath, nextConfig)
expect(cliOutput).toContain(
'https://nextjs.org/docs/messages/export-path-mismatch'
......@@ -463,13 +472,15 @@ createNextDescribe(
describe('API routes export', () => {
it('Should throw if a route is matched', async () => {
const outdir = 'outApi'
const nextConfig = await next.readFile(nextConfigPath)
await next.patchFile(
nextConfigPath,
nextConfig.replace('// API route', `'/data': { page: '/api/data' },`)
nextConfig
.replace('// API route', `'/data': { page: '/api/data' },`)
.replace(`distDir: 'out'`, `distDir: '${outdir}'`)
)
const outdir = 'outApi'
const { cliOutput } = await next.export({ outdir })
const { cliOutput } = await next.build()
await next.patchFile(nextConfigPath, nextConfig)
expect(cliOutput).toContain(
......@@ -483,12 +494,12 @@ createNextDescribe(
const tmpOutdir = 'exportTrailingSlash-out'
await next.patchFile(
nextConfigPath,
nextConfig.replace(`trailingSlash: true`, `exportTrailingSlash: true`)
nextConfig
.replace(`trailingSlash: true`, `exportTrailingSlash: true`)
.replace(`distDir: 'out'`, `distDir: '${tmpOutdir}'`)
)
await next.build()
await next.export({ outdir: tmpOutdir })
await next.patchFile(nextConfigPath, nextConfig)
expect(await fileExist(path.join(tmpOutdir, '404/index.html'))).toBeTrue()
})
}
......
module.exports = (phase) => {
return {
output: 'export',
distDir: 'out',
publicRuntimeConfig: {
foo: 'foo',
},
......
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import { join } from 'path'
describe('fallback export error', () => {
......@@ -11,19 +10,21 @@ describe('fallback export error', () => {
files: {
pages: new FileRef(join(__dirname, 'pages')),
},
nextConfig: {
output: 'export',
},
skipStart: true,
})
})
afterAll(() => next.destroy())
it('should have built', async () => {
const html = await renderViaHTTP(next.url, '/')
expect(html).toContain('index page')
const result = await next.build()
expect(result.exitCode).toBe(0)
})
it('should not error with default exportPathMap', async () => {
await next.stop()
const result = await next.export()
const result = await next.build()
console.log(result.cliOutput)
expect(result.exitCode).toBe(0)
......@@ -33,11 +34,11 @@ describe('fallback export error', () => {
})
it('should not error with valid exportPathMap', async () => {
await next.stop()
await next.patchFile(
'next.config.js',
`
module.exports = {
output: 'export',
exportPathMap() {
return {
'/': { page: '/' },
......@@ -48,7 +49,7 @@ describe('fallback export error', () => {
)
try {
const result = await next.export()
const result = await next.build()
console.log(result.cliOutput)
expect(result.exitCode).toBe(0)
......@@ -66,6 +67,7 @@ describe('fallback export error', () => {
'next.config.js',
`
module.exports = {
output: 'export',
exportPathMap() {
return {
'/': { page: '/' },
......@@ -77,7 +79,7 @@ describe('fallback export error', () => {
)
try {
const result = await next.export()
const result = await next.build()
console.log(result.cliOutput)
expect(result.exitCode).toBe(1)
......
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