Unverified Commit bce75ae9 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add checking for corresponding pages for link tags (#6719)

parent 2cc8365d
......@@ -11,13 +11,16 @@ export async function loadComponents(distDir: string, buildId: string, pathname:
const documentPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_document')
const appPath = join(distDir, SERVER_DIRECTORY, CLIENT_STATIC_FILES_PATH, buildId, 'pages', '_app')
const [buildManifest, reactLoadableManifest, Component, Document, App] = await Promise.all([
const [buildManifest, reactLoadableManifest, pageData, Document, App] = await Promise.all([
require(join(distDir, BUILD_MANIFEST)),
require(join(distDir, REACT_LOADABLE_MANIFEST)),
interopDefault(requirePage(pathname, distDir, opts)),
requirePage(pathname, distDir, opts),
interopDefault(require(documentPath)),
interopDefault(require(appPath)),
])
return {buildManifest, reactLoadableManifest, Component, Document, App}
const Component = interopDefault(pageData.mod)
const { hasAmp } = pageData
return {buildManifest, reactLoadableManifest, Component, Document, App, hasAmp}
}
......@@ -285,8 +285,8 @@ export default class Server {
query: ParsedUrlQuery = {},
opts: any,
) {
const result = await loadComponents(this.distDir, this.buildId, pathname, { amphtml: !!opts.amphtml })
return renderToHTML(req, res, pathname, query, { ...result, ...opts })
const result = await loadComponents(this.distDir, this.buildId, pathname, opts)
return renderToHTML(req, res, pathname, query, { ...result, ...opts, hasAmp: result.hasAmp })
}
public async renderToHTML(
......@@ -294,7 +294,10 @@ export default class Server {
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {},
{ amphtml }: { amphtml?: boolean } = {},
{ amphtml, hasAmp }: {
amphtml?: boolean,
hasAmp?: boolean,
} = {},
): Promise<string | null> {
try {
// To make sure the try/catch is executed
......@@ -303,7 +306,7 @@ export default class Server {
res,
pathname,
query,
{ ...this.renderOpts, amphtml },
{ ...this.renderOpts, amphtml, hasAmp },
)
return html
} catch (err) {
......
......@@ -116,6 +116,7 @@ type RenderOpts = {
nextExport?: boolean
dev?: boolean
amphtml?: boolean
hasAmp?: boolean
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
Component: React.ComponentType
......@@ -140,6 +141,7 @@ function renderDocument(
err,
dev,
amphtml,
hasAmp,
staticMarkup,
devFiles,
files,
......@@ -150,6 +152,7 @@ function renderDocument(
pathname: string
query: ParsedUrlQuery
amphtml: boolean
hasAmp: boolean,
dynamicImportsIds: string[]
dynamicImports: ManifestItem[]
files: string[]
......@@ -175,6 +178,7 @@ function renderDocument(
}}
ampEnabled={ampEnabled}
amphtml={amphtml}
hasAmp={hasAmp}
staticMarkup={staticMarkup}
devFiles={devFiles}
files={files}
......@@ -200,6 +204,7 @@ export async function renderToHTML(
dev = false,
staticMarkup = false,
amphtml = false,
hasAmp = false,
App,
Document,
Component,
......@@ -310,6 +315,7 @@ export async function renderToHTML(
docProps,
pathname,
amphtml,
hasAmp,
query,
dynamicImportsIds,
dynamicImports,
......
......@@ -51,7 +51,21 @@ export function getPagePath(page: string, distDir: string, opts: PagePathOptions
return join(serverBuildPath, pagesManifest[page])
}
export function requirePage(page: string, distDir: string, opts?: PagePathOptions): any {
export function requirePage(page: string, distDir: string, opts: PagePathOptions = {}): any {
const pagePath = getPagePath(page, distDir, opts)
return require(pagePath)
const isAmp = pagePath.indexOf('.amp.') > -1
let hasAmp = false
if (!isAmp) {
try {
const ampPage = getPagePath(page, distDir, { amphtml: true })
hasAmp = Boolean(ampPage && ampPage.indexOf('.amp') > -1)
} catch (_) {}
}
opts.amphtml = opts.amphtml || isAmp
return {
hasAmp,
mod: require(pagePath),
}
}
......@@ -150,6 +150,7 @@ export class Head extends Component {
ampEnabled,
styles,
amphtml,
hasAmp,
assetPrefix,
__NEXT_DATA__,
} = this.context._documentProps
......@@ -201,7 +202,7 @@ export class Head extends Component {
name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1"
/>
<link rel="canonical" href={page} />
<link rel="canonical" href={page.split('.amp')[0]} />
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link
rel="preload"
......@@ -240,7 +241,7 @@ export class Head extends Component {
)}
{!amphtml && (
<>
{ampEnabled && <link rel="amphtml" href={`${page}?amp=1`} />}
{ampEnabled && hasAmp && <link rel="amphtml" href={`${page}?amp=1`} />}
{page !== '/_error' && (
<link
rel="preload"
......
......@@ -126,6 +126,7 @@ export default class DevServer extends Server {
const result = await this.hotReloader.ensurePage(pathname, options.amphtml, this.nextConfig.experimental.amp)
pathname = result.pathname
options.amphtml = options.amphtml || result.isAmp
options.hasAmp = result.hasAmp
} catch (err) {
if (err.code === 'ENOENT') {
res.statusCode = 404
......
......@@ -234,7 +234,11 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
const absolutePagePath = pagePath.startsWith('next/dist/pages') ? require.resolve(pagePath) : join(pagesDir, pagePath)
page = posix.normalize(pageUrl)
const result = { isAmp, pathname: page }
const result = {
isAmp,
pathname: page,
hasAmp: !isAmp && await findPageFile(pagesDir, normalizedPagePath, pageExtensions, !isAmp, ampEnabled)
}
await new Promise((resolve, reject) => {
// Makes sure the page that is being kept in on-demand-entries matches the webpack output
......
export default () => <div>No AMP for me...</div>
export default () => <div>Only AMP for me...</div>
......@@ -156,13 +156,43 @@ describe('AMP Usage', () => {
).toBe('/use-amp-hook')
})
it('should render a canonical regardless of amp-only status (implicit)', async () => {
const html = await renderViaHTTP(appPort, '/only-amp')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('/only-amp')
})
it('should render a canonical regardless of amp-only status (explicit)', async () => {
const html = await renderViaHTTP(appPort, '/only-amp?amp=1')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
$('link[rel=canonical]')
.first()
.attr('href')
).toBe('/only-amp')
})
it('should not render amphtml link tag with no AMP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect(
$('link[rel=amphtml]')
.first()
.attr('href')
).not.toBeTruthy()
})
it('should remove conflicting amp tags', async () => {
const html = await renderViaHTTP(appPort, '/conflicting-tag?amp=1')
const $ = cheerio.load(html)
await validateAMP(html)
expect(
$('meta[name=viewport]').attr('content')
).not.toBe('something :p')
expect($('meta[name=viewport]').attr('content')).not.toBe('something :p')
})
})
......@@ -182,7 +212,9 @@ describe('AMP Usage', () => {
it('should remove sourceMaps from styles', async () => {
const html = await renderViaHTTP(appPort, '/styled?amp=1')
const $ = cheerio.load(html)
const styles = $('style[amp-custom]').first().text()
const styles = $('style[amp-custom]')
.first()
.text()
expect(styles).not.toMatch(/\/\*@ sourceURL=.*?\*\//)
expect(styles).not.toMatch(/\/\*# sourceMappingURL=.*\*\//)
......
......@@ -59,17 +59,17 @@ describe('getPagePath', () => {
describe('requirePage', () => {
it('Should require /index.js when using /', async () => {
const page = await requirePage('/', distDir)
const page = (await requirePage('/', distDir)).mod
expect(page.test).toBe('hello')
})
it('Should require /index.js when using /index', async () => {
const page = await requirePage('/index', distDir)
const page = (await requirePage('/index', distDir)).mod
expect(page.test).toBe('hello')
})
it('Should require /world.js when using /world', async () => {
const page = await requirePage('/world', distDir)
const page = (await requirePage('/world', distDir)).mod
expect(page.test).toBe('world')
})
......
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