Unverified Commit bef9b561 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Update filename generation for client-side compilation (#14279)

Updates the way filenames are generated for browser compilation.
Notably:
- All entry bundles now have hashes in production, this includes pages (previously pages used a buildId in the path)
- The AmpFiles no longer depends on hardcoded bundle names, it uses the buildManifest instead (internals)
- All cases where we match the page name from the chunk/entrypoint name now use the same function `getRouteFromEntrypoint` (internals)
- In development we no longer include the "faked" `buildId` set to `development` for page files, instead we just use the `/_next/static/pages` path (was `/_next/static/development/pages`). This was changed as it caused unneeded complexity and makes generating the bundles easier (internals)
- Updated tons of tests to be more resilient to these changes by relying on the buildManifest instead of hardcoded paths (internals)

Follow up of these PRs:
https://github.com/vercel/next.js/pull/13759
https://github.com/vercel/next.js/pull/13870
https://github.com/vercel/next.js/pull/13937
https://github.com/vercel/next.js/pull/14130
https://github.com/vercel/next.js/pull/14176
https://github.com/vercel/next.js/pull/14268


Fixes #6303
Fixes #12087 
Fixes #1948
Fixes #4368
Fixes #4255
Fixes #2548
parent 76673fd8
......@@ -97,10 +97,11 @@ export function createEntrypoints(
Object.keys(pages).forEach((page) => {
const absolutePagePath = pages[page]
const bundleFile = `${normalizePagePath(page)}.js`
const bundleFile = normalizePagePath(page)
const isApiRoute = page.match(API_ROUTE)
const bundlePath = join('static', 'BUILD_ID', 'pages', bundleFile)
const clientBundlePath = join('static', 'pages', bundleFile)
const serverBundlePath = join('static', 'BUILD_ID', 'pages', bundleFile)
const isLikeServerless = isTargetLikeServerless(target)
......@@ -114,7 +115,7 @@ export function createEntrypoints(
serverlessLoaderOptions
)}!`
} else if (isApiRoute || target === 'server') {
server[bundlePath] = [absolutePagePath]
server[serverBundlePath] = [absolutePagePath]
} else if (isLikeServerless && page !== '/_app' && page !== '/_document') {
const serverlessLoaderOptions: ServerlessLoaderQuery = {
page,
......@@ -143,7 +144,7 @@ export function createEntrypoints(
// might cause the router to not be able to load causing hydration
// to fail
client[bundlePath] =
client[clientBundlePath] =
page === '/_app'
? [pageLoader, require.resolve('../client/router')]
: pageLoader
......
......@@ -415,7 +415,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
error.indexOf('__next_polyfill__') > -1
) {
throw new Error(
'> webpack config.resolve.alias was incorrectly overriden. https://err.sh/vercel/next.js/invalid-resolve-alias'
'> webpack config.resolve.alias was incorrectly overridden. https://err.sh/vercel/next.js/invalid-resolve-alias'
)
}
throw new Error('> Build failed because of webpack errors')
......
......@@ -679,26 +679,24 @@ export default async function getBaseWebpackConfig(
},
output: {
path: outputPath,
filename: ({ chunk }: { chunk: { name: string } }) => {
// Use `[name]-[contenthash].js` in production
if (
!dev &&
(chunk.name === CLIENT_STATIC_FILES_RUNTIME_MAIN ||
chunk.name === CLIENT_STATIC_FILES_RUNTIME_WEBPACK ||
chunk.name === CLIENT_STATIC_FILES_RUNTIME_POLYFILLS)
) {
return chunk.name.replace(/\.js$/, '-[contenthash].js')
}
if (chunk.name.includes('BUILD_ID')) {
return escapePathVariables(chunk.name).replace(
'BUILD_ID',
isServer || dev ? buildId : '[contenthash]'
)
}
filename: isServer
? ({ chunk }: { chunk: { name: string } }) => {
// Use `[name]-[contenthash].js` in production
if (chunk.name.includes('BUILD_ID')) {
return (
escapePathVariables(chunk.name).replace(
'BUILD_ID',
isServer || dev ? buildId : '[contenthash]'
) + '.js'
)
}
return '[name]'
},
return '[name].js'
}
: // Client compilation only
dev
? '[name].js'
: '[name]-[chunkhash].js',
libraryTarget: isServer ? 'commonjs2' : 'var',
hotUpdateChunkFilename: isWebpack5
? 'static/webpack/[id].[fullhash].hot-update.js'
......
......@@ -7,6 +7,7 @@ import {
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
} from '../../../next-server/lib/constants'
import { BuildManifest } from '../../../next-server/server/get-page-files'
import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
......@@ -62,6 +63,7 @@ export default class BuildManifestPlugin {
const assetMap: BuildManifest = {
polyfillFiles: [],
devFiles: [],
ampDevFiles: [],
lowPriorityFiles: [],
pages: { '/_app': [] },
ampFirstPages: [],
......@@ -98,6 +100,19 @@ export default class BuildManifestPlugin {
assetMap.devFiles = reactRefreshChunk?.files.filter(isJsFile) ?? []
for (const entrypoint of compilation.entrypoints.values()) {
const isAmpRuntime =
entrypoint.name === CLIENT_STATIC_FILES_RUNTIME_AMP
if (isAmpRuntime) {
for (const file of entrypoint.getFiles()) {
if (!(isJsFile(file) || file.endsWith('.css'))) {
continue
}
assetMap.ampDevFiles.push(file.replace(/\\/g, '/'))
}
continue
}
const pagePath = getRouteFromEntrypoint(entrypoint.name)
if (!pagePath) {
......
import webpack from 'webpack'
import { RawSource } from 'webpack-sources'
import { join, relative, dirname } from 'path'
import { IS_BUNDLED_PAGE_REGEX } from '../../../next-server/lib/constants'
import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
const SSR_MODULE_CACHE_FILENAME = 'ssr-module-cache.js'
// By default webpack keeps initialized modules per-module.
......@@ -44,7 +43,8 @@ export default class NextJsSsrImportPlugin {
// If the chunk is not part of the pages directory we have to keep the original behavior,
// otherwise webpack will error out when the file is used before the compilation finishes
// this is the case with mini-css-extract-plugin
if (!IS_BUNDLED_PAGE_REGEX.exec(chunk.name)) {
if (!getRouteFromEntrypoint(chunk.name)) {
return originalFn(source, chunk)
}
const pagePath = join(outputPath, dirname(chunk.name))
......
import { join } from 'path'
import { promises } from 'fs'
import { IS_BUNDLED_PAGE_REGEX } from '../../../next-server/lib/constants'
import { Compiler } from 'webpack'
import getRouteFromEntrypoint from '../../../next-server/server/get-route-from-entrypoint'
// Makes sure removed pages are removed from `.next` in development
export class UnlinkRemovedPagesPlugin {
prevAssets: any
......@@ -15,7 +14,7 @@ export class UnlinkRemovedPagesPlugin {
'NextJsUnlinkRemovedPages',
(compilation, callback) => {
const removed = Object.keys(this.prevAssets).filter(
(a) => IS_BUNDLED_PAGE_REGEX.test(a) && !compilation.assets[a]
(a) => getRouteFromEntrypoint(a) && !compilation.assets[a]
)
this.prevAssets = compilation.assets
......
......@@ -248,9 +248,9 @@ export default class PageLoader {
route = normalizeRoute(route)
let scriptRoute = getAssetPath(route)
const url = `${this.assetPrefix}/_next/static/${encodeURIComponent(
this.buildId
)}/pages${encodeURI(scriptRoute)}.js`
const url = `${this.assetPrefix}/_next/static/pages${encodeURI(
scriptRoute
)}.js`
this.loadScript(url, route)
}
}
......
......@@ -21,17 +21,15 @@ export const AMP_RENDER_TARGET = '__NEXT_AMP_RENDER_TARGET__'
export const STRING_LITERAL_DROP_BUNDLE = '__NEXT_DROP_CLIENT_FILE__'
export const CLIENT_STATIC_FILES_RUNTIME_PATH = `${CLIENT_STATIC_FILES_PATH}/${CLIENT_STATIC_FILES_RUNTIME}`
// static/runtime/main.js
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/main.js`
export const CLIENT_STATIC_FILES_RUNTIME_MAIN = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/main`
// static/runtime/react-refresh.js
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/react-refresh.js`
export const CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/react-refresh`
// static/runtime/amp.js
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/amp.js`
export const CLIENT_STATIC_FILES_RUNTIME_AMP = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/amp`
// static/runtime/webpack.js
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/webpack.js`
export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/webpack`
// static/runtime/polyfills.js
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/polyfills.js`
// matches static/<buildid>/pages/<page>.js
export const IS_BUNDLED_PAGE_REGEX = /^static[/\\][^/\\]+[/\\]pages.*\.js$/
export const CLIENT_STATIC_FILES_RUNTIME_POLYFILLS = `${CLIENT_STATIC_FILES_RUNTIME_PATH}/polyfills`
export const TEMPORARY_REDIRECT_STATUS = 307
export const PERMANENT_REDIRECT_STATUS = 308
export const STATIC_PROPS_ID = '__N_SSG'
......
......@@ -2,6 +2,7 @@ import { normalizePagePath, denormalizePagePath } from './normalize-page-path'
export type BuildManifest = {
devFiles: string[]
ampDevFiles: string[]
polyfillFiles: string[]
lowPriorityFiles: string[]
pages: {
......
import { denormalizePagePath } from './normalize-page-path'
// matches static/<buildid>/pages/:page*.js
const ROUTE_NAME_REGEX = /^static[/\\][^/\\]+[/\\]pages[/\\](.*)\.js$/
const SERVERLESS_ROUTE_NAME_REGEX = /^pages[/\\](.*)\.js$/
const ROUTE_NAME_REGEX = /^static[/\\][^/\\]+[/\\]pages[/\\](.*)$/
// matches pages/:page*.js
const SERVERLESS_ROUTE_NAME_REGEX = /^pages[/\\](.*)$/
// matches static/pages/:page*.js
const BROWSER_ROUTE_NAME_REGEX = /^static[/\\]pages[/\\](.*)$/
export default function getRouteFromEntrypoint(
entryFile: string,
isServerlessLike: boolean = false
): string | null {
const result = (isServerlessLike
? SERVERLESS_ROUTE_NAME_REGEX
: ROUTE_NAME_REGEX
).exec(entryFile)
function matchBundle(regex: RegExp, input: string): string | null {
const result = regex.exec(input)
if (!result) {
return null
}
const pagePath = result[1]
return denormalizePagePath(`/${result[1]}`)
}
if (!pagePath) {
return null
export default function getRouteFromEntrypoint(
entryFile: string,
isServerlessLike: boolean = false
): string | null {
let pagePath = matchBundle(
isServerlessLike ? SERVERLESS_ROUTE_NAME_REGEX : ROUTE_NAME_REGEX,
entryFile
)
if (pagePath) {
return pagePath
}
return denormalizePagePath(`/${pagePath}`)
// Potentially the passed item is a browser bundle so we try to match that also
return matchBundle(BROWSER_ROUTE_NAME_REGEX, entryFile)
}
......@@ -372,6 +372,7 @@ export default class Server {
params.path[0] === 'css' ||
params.path[0] === 'media' ||
params.path[0] === this.buildId ||
params.path[0] === 'pages' ||
params.path[1] === 'pages'
) {
this.setImmutableAssetCacheControl(res)
......
import PropTypes from 'prop-types'
import React, { useContext, Component } from 'react'
import flush from 'styled-jsx/server'
import {
AMP_RENDER_TARGET,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
} from '../next-server/lib/constants'
import { AMP_RENDER_TARGET } from '../next-server/lib/constants'
import { DocumentContext as DocumentComponentContext } from '../next-server/lib/document-context'
import {
DocumentContext,
......@@ -619,10 +614,9 @@ export class NextScript extends Component<OriginProps> {
return null
}
const AmpDevFiles = [
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
const ampDevFiles = [
...buildManifest.devFiles,
...buildManifest.ampDevFiles,
]
return (
......@@ -643,19 +637,17 @@ export class NextScript extends Component<OriginProps> {
data-ampdevmode
/>
)}
{AmpDevFiles
? AmpDevFiles.map((file) => (
<script
key={file}
src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
data-ampdevmode
/>
))
: null}
{ampDevFiles.map((file) => (
<script
key={file}
src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`}
nonce={this.props.nonce}
crossOrigin={
this.props.crossOrigin || process.env.__NEXT_CROSS_ORIGIN
}
data-ampdevmode
/>
))}
</>
)
}
......
......@@ -15,7 +15,6 @@ import {
BLOCKED_PAGES,
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
IS_BUNDLED_PAGE_REGEX,
} from '../next-server/lib/constants'
import { __ApiPreviewProps } from '../next-server/server/api-utils'
import { route } from '../next-server/server/router'
......@@ -80,7 +79,7 @@ function addCorsSupport(req: IncomingMessage, res: ServerResponse) {
}
const matchNextPageBundleRequest = route(
'/_next/static/:buildId/pages/:path*.js(\\.map|)'
'/_next/static/pages/:path*.js(\\.map|)'
)
// Recursively look up the issuer till it ends up at the root
......@@ -109,7 +108,7 @@ function erroredPages(
}
// Only pages have to be reloaded
if (!IS_BUNDLED_PAGE_REGEX.test(name)) {
if (!getRouteFromEntrypoint(name)) {
continue
}
......@@ -195,15 +194,13 @@ export default class HotReloader {
parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl
const params = matchNextPageBundleRequest(pathname)
const params: { path: string[] } | null = matchNextPageBundleRequest(
pathname
)
if (!params) {
return {}
}
if (params.buildId !== this.buildId) {
return {}
}
const page = denormalizePagePath(`/${params.path.join('/')}`)
if (page === '/_error' || BLOCKED_PAGES.indexOf(page) === -1) {
try {
......@@ -383,7 +380,7 @@ export default class HotReloader {
// We only watch `_document` for changes on the server compilation
// the rest of the files will be triggered by the client compilation
const documentChunk = compilation.chunks.find(
(c) => c.name === normalize(`static/BUILD_ID/pages/_document.js`)
(c) => c.name === normalize(`static/BUILD_ID/pages/_document`)
)
// If the document chunk can't be found we do nothing
if (!documentChunk) {
......@@ -415,7 +412,7 @@ export default class HotReloader {
const chunkNames = new Set(
compilation.chunks
.map((c) => c.name)
.filter((name) => IS_BUNDLED_PAGE_REGEX.test(name))
.filter((name) => !!getRouteFromEntrypoint(name))
)
if (this.initialized) {
......
......@@ -55,7 +55,15 @@ export default function onDemandEntryHandler(
) {
const { compilers } = multiCompiler
const invalidator = new Invalidator(devMiddleware, multiCompiler)
let entries: any = {}
let entries: {
[page: string]: {
serverBundlePath: string
clientBundlePath: string
absolutePagePath: string
status?: typeof ADDED | typeof BUILDING | typeof BUILT
lastActiveTime?: number
}
} = {}
let lastAccessPages = ['']
let doneCallbacks: EventEmitter | null = new EventEmitter()
......@@ -65,11 +73,16 @@ export default function onDemandEntryHandler(
(compilation: webpack.compilation.Compilation) => {
invalidator.startBuilding()
const isClientCompilation = compiler.name === 'client'
const allEntries = Object.keys(entries).map(async (page) => {
if (compiler.name === 'client' && page.match(API_ROUTE)) {
if (isClientCompilation && page.match(API_ROUTE)) {
return
}
const { name, absolutePagePath } = entries[page]
const {
serverBundlePath,
clientBundlePath,
absolutePagePath,
} = entries[page]
const pageExists = await isWriteable(absolutePagePath)
if (!pageExists) {
// page was removed
......@@ -82,11 +95,16 @@ export default function onDemandEntryHandler(
page,
absolutePagePath,
}
return addEntry(compilation, compiler.context, name, [
compiler.name === 'client'
? `next-client-pages-loader?${stringify(pageLoaderOpts)}!`
: absolutePagePath,
])
return addEntry(
compilation,
compiler.context,
isClientCompilation ? clientBundlePath : serverBundlePath,
[
isClientCompilation
? `next-client-pages-loader?${stringify(pageLoaderOpts)}!`
: absolutePagePath,
]
)
})
return Promise.all(allEntries).catch((err) => console.error(err))
......@@ -209,8 +227,9 @@ export default function onDemandEntryHandler(
pageUrl = pageUrl === '' ? '/' : pageUrl
const bundleFile = `${normalizePagePath(pageUrl)}.js`
const name = join('static', 'BUILD_ID', 'pages', bundleFile)
const bundleFile = normalizePagePath(pageUrl)
const serverBundlePath = join('static', 'BUILD_ID', 'pages', bundleFile)
const clientBundlePath = join('static', 'pages', bundleFile)
const absolutePagePath = pagePath.startsWith('next/dist/pages')
? require.resolve(pagePath)
: join(pagesDir, pagePath)
......@@ -236,7 +255,12 @@ export default function onDemandEntryHandler(
Log.event(`build page: ${normalizedPage}`)
entries[normalizedPage] = { name, absolutePagePath, status: ADDED }
entries[normalizedPage] = {
serverBundlePath,
clientBundlePath,
absolutePagePath,
status: ADDED,
}
doneCallbacks!.once(normalizedPage, handleCallback)
invalidator.invalidate()
......
......@@ -12,6 +12,8 @@ import {
nextBuild,
nextStart,
nextExport,
getPageFileFromBuildManifest,
getPageFileFromPagesManifest,
} from 'next-test-utils'
import json from '../big.json'
......@@ -355,31 +357,13 @@ function runTests(dev = false) {
if (dev) {
it('should compile only server code in development', async () => {
await fetchViaHTTP(appPort, '/')
await fetchViaHTTP(appPort, '/api/users')
// Normal page
expect(
await fs.exists(
join(appDir, `/.next/static/development/pages/index.js`)
)
).toBeTruthy()
expect(
await fs.exists(
join(appDir, `/.next/server/static/development/pages/index.js`)
)
).toBeTruthy()
// API page
expect(
await fs.exists(
join(appDir, `/.next/static/development/pages/api/users.js`)
)
).toBeFalsy()
expect(
await fs.exists(
join(appDir, `/.next/server/static/development/pages/api/users.js`)
)
).toBeTruthy()
expect(() => getPageFileFromBuildManifest(appDir, '/api/users')).toThrow(
/No files for page/
)
expect(getPageFileFromPagesManifest(appDir, '/api/users')).toBeTruthy()
})
it('should show warning when the API resolves without ending the request in dev mode', async () => {
......
......@@ -75,7 +75,7 @@ const runTests = (context, dev = false) => {
for (const link of links) {
const href = await link.getAttribute('href')
if (href.match(/(gsp|gssp|other-page)\.js$/)) {
if (href.match(/(gsp|gssp|other-page)-.*?\.js$/)) {
found.add(href)
}
if (href.match(/gsp\.json$/)) {
......
......@@ -52,10 +52,17 @@ describe('Build Output', () => {
)
)[1]
const parseSharedSize = (sharedPartName) =>
stdout.match(
const parseSharedSize = (sharedPartName) => {
const matches = stdout.match(
new RegExp(`${sharedPartName} .*? ((?:\\d|\\.){1,} (?:\\w{1,}))`)
)[1]
)
if (!matches) {
throw new Error(`Could not match ${sharedPartName}`)
}
return matches[1]
}
const indexSize = parsePageSize('/')
const indexFirstLoad = parsePageFirstLoad('/')
......@@ -64,7 +71,7 @@ describe('Build Output', () => {
const err404FirstLoad = parsePageFirstLoad('/404')
const sharedByAll = parseSharedSize('shared by all')
const _appSize = parseSharedSize('_app\\.js')
const _appSize = parseSharedSize('_app\\..*?\\.js')
const webpackSize = parseSharedSize('webpack\\..*?\\.js')
const mainSize = parseSharedSize('main\\..*?\\.js')
const frameworkSize = parseSharedSize('framework\\..*?\\.js')
......
......@@ -4,6 +4,9 @@ import cheerio from 'cheerio'
import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST } from 'next/constants'
import { join } from 'path'
import url from 'url'
import { getPageFileFromBuildManifest } from 'next-test-utils'
const appDir = join(__dirname, '../')
export default function (render, fetch) {
async function get$(path, query) {
......@@ -267,9 +270,11 @@ export default function (render, fetch) {
test('should expose the compiled page file in development', async () => {
await fetch('/stateless') // make sure the stateless page is built
const clientSideJsRes = await fetch(
'/_next/development/static/development/pages/stateless.js'
const statelessPageFile = getPageFileFromBuildManifest(
appDir,
'/stateless'
)
const clientSideJsRes = await fetch(join('/_next', statelessPageFile))
expect(clientSideJsRes.status).toBe(200)
const clientSideJsBody = await clientSideJsRes.text()
expect(clientSideJsBody).toMatch(/My component!/)
......
......@@ -12,7 +12,7 @@ describe('Invalid resolve alias', () => {
})
expect(stderr).toMatch(
'webpack config.resolve.alias was incorrectly overriden. https://err.sh'
'webpack config.resolve.alias was incorrectly overridden. https://err.sh'
)
})
})
......@@ -28,7 +28,26 @@ describe('Failing to load _error', () => {
await browser.eval(`window.beforeNavigate = true`)
await browser.elementByCss('#to-broken').moveTo()
await browser.waitForElementByCss('script[src*="broken.js"')
await check(
async () => {
const scripts = await browser.elementsByCss('script')
let found = false
for (const script of scripts) {
const src = await script.getAttribute('src')
if (src.includes('broken-')) {
found = true
break
}
}
return found
},
{
test(content) {
return content === true
},
}
)
const errorPageFilePath = getPageFileFromBuildManifest(appDir, '/_error')
// remove _error client bundle so that it can't be loaded
......
......@@ -2,7 +2,12 @@
import { join } from 'path'
import getPort from 'get-port'
import { fetchViaHTTP, initNextServerScript, killApp } from 'next-test-utils'
import {
fetchViaHTTP,
initNextServerScript,
killApp,
getPageFileFromBuildManifest,
} from 'next-test-utils'
import clone from 'clone'
const appDir = join(__dirname, '../')
......@@ -47,9 +52,11 @@ describe('FileSystemPublicRoutes', () => {
it('should still handle /_next routes', async () => {
await fetch('/exportpathmap-route') // make sure it's built
const res = await fetch(
'/_next/static/development/pages/exportpathmap-route.js'
const pageFile = getPageFileFromBuildManifest(
appDir,
'/exportpathmap-route'
)
const res = await fetch(join('/_next', pageFile))
expect(res.status).toBe(200)
const body = await res.text()
expect(body).toMatch(/exportpathmap was here/)
......
......@@ -13,8 +13,10 @@ import {
waitFor,
check,
getBrowserBodyText,
getPageFileFromBuildManifest,
} from 'next-test-utils'
const appDir = join(__dirname, '../')
const context = {}
const doPing = (page) => {
......@@ -43,7 +45,7 @@ describe('On Demand Entries', () => {
it('should pass', () => {})
beforeAll(async () => {
context.appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort)
context.server = await launchApp(appDir, context.appPort)
})
afterAll(() => {
killApp(context.server)
......@@ -58,34 +60,33 @@ describe('On Demand Entries', () => {
})
it('should compile pages for JSON page requests', async () => {
await renderViaHTTP(context.appPort, '/about')
const pageFile = getPageFileFromBuildManifest(appDir, '/about')
const pageContent = await renderViaHTTP(
context.appPort,
'/_next/static/development/pages/about.js'
join('/_next', pageFile)
)
expect(pageContent.includes('About Page')).toBeTruthy()
})
it('should dispose inactive pages', async () => {
const indexPagePath = resolve(
__dirname,
'../.next/static/development/pages/index.js'
)
await renderViaHTTP(context.appPort, '/')
await doPing('/')
const indexPage = getPageFileFromBuildManifest(appDir, '/')
const indexPagePath = resolve(__dirname, join('../.next', indexPage))
expect(existsSync(indexPagePath)).toBeTruthy()
// Render two pages after the index, since the server keeps at least two pages
await renderViaHTTP(context.appPort, '/about')
await doPing('/about')
const aboutPagePath = resolve(
__dirname,
'../.next/static/development/pages/about.js'
)
const aboutPage = getPageFileFromBuildManifest(appDir, '/about')
const aboutPagePath = resolve(__dirname, join('../.next', aboutPage))
await renderViaHTTP(context.appPort, '/third')
await doPing('/third')
const thirdPagePath = resolve(
__dirname,
'../.next/static/development/pages/third.js'
)
const thirdPage = getPageFileFromBuildManifest(appDir, '/third')
const thirdPagePath = resolve(__dirname, join('../.next', thirdPage))
// Wait maximum of jest.setTimeout checking
// for disposing /about
......
......@@ -212,7 +212,7 @@ describe('Prefetching Links in viewport', () => {
expect(hrefs).toEqual([...new Set(hrefs)])
// Verify encoding
expect(hrefs.some((e) => e.includes(`%5Bhello%5D.js`))).toBe(true)
expect(hrefs.some((e) => e.includes(`%5Bhello%5D-`))).toBe(true)
})
it('should not add an another observer for a prefetched page', async () => {
......
/* eslint-env jest */
import { join } from 'path'
import { killApp, findPort, launchApp, fetchViaHTTP } from 'next-test-utils'
import {
killApp,
findPort,
launchApp,
fetchViaHTTP,
getPageFileFromBuildManifest,
renderViaHTTP,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 2)
......@@ -12,10 +19,10 @@ let app
const runTest = (mode = 'server') => {
it('supports trailing slash', async () => {
const res = await fetchViaHTTP(
appPort,
'/_next/static/development/pages/index.js'
)
// Make sure the page is built before getting the file
await renderViaHTTP(appPort, '/')
const file = getPageFileFromBuildManifest(appDir, '/')
const res = await fetchViaHTTP(appPort, join('/_next', file))
expect(res.status).toBe(200)
})
......
......@@ -494,7 +494,7 @@ export function normalizeRegEx(src) {
}
export function getBuildManifest(dir) {
return require(path.join(dir, '.next/build-manifest.json'))
return JSON.parse(readFileSync(path.join(dir, '.next/build-manifest.json')))
}
export function getPageFileFromBuildManifest(dir, page) {
......
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