Commit cf889d60 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Re-add experimental amp config (#7030)

* Update amphtml and canonical rels, put amp behind
experimental flag again, and update checking for amp query

* Fix typescript error

* Re-add flag to next.config.js
parent 016c197b
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-amp)
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/amp)
# Google AMP
......@@ -9,9 +9,9 @@
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example with-amp with-amp-app
npx create-next-app --example amp amp-app
# or
yarn create next-app --example with-amp with-amp-app
yarn create next-app --example amp amp-app
```
### Download manually
......@@ -19,8 +19,8 @@ yarn create next-app --example with-amp with-amp-app
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-amp
cd with-amp
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/amp
cd amp
```
Install it and run:
......@@ -41,4 +41,4 @@ now
## The idea behind the example
This example shows how to create AMP pages using Next.js. It shows a normal page (non-AMP), an AMP only page, and a hybrid AMP page.
This example shows how to create AMP pages using Next.js and the experimental AMP feature. It shows a normal page (non-AMP), an AMP only page, and a hybrid AMP page.
module.exports = {
experimental: {
amp: true
}
}
{
"name": "with-amp",
"name": "amp",
"version": "1.0.0",
"scripts": {
"dev": "next",
......
......@@ -22,6 +22,7 @@ const defaultConfig = {
pagesBufferLength: 2
},
experimental: {
amp: false,
noDirtyAmp: false,
cpus: Math.max(
1,
......
......@@ -119,6 +119,7 @@ type RenderOpts = {
buildId: string
dynamicBuildId?: boolean
runtimeConfig?: { [key: string]: any }
dangerousAsPath: string
assetPrefix?: string
err?: Error | null
nextExport?: boolean
......@@ -151,6 +152,7 @@ function renderDocument(
runtimeConfig,
nextExport,
dynamicImportsIds,
dangerousAsPath,
err,
dev,
ampPath,
......@@ -167,6 +169,7 @@ function renderDocument(
docProps: any
pathname: string
query: ParsedUrlQuery
dangerousAsPath: string
ampPath: string,
amphtml: boolean
hasAmp: boolean,
......@@ -196,6 +199,7 @@ function renderDocument(
dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
}}
dangerousAsPath={dangerousAsPath}
ampPath={ampPath}
amphtml={amphtml}
hasAmp={hasAmp}
......@@ -307,7 +311,7 @@ export async function renderToHTML(
const ampMode = {
enabled: false,
hasQuery: Boolean(query.amp),
hasQuery: Boolean(query.amp && /^(y|yes|true|1)/i.test(query.amp.toString())),
}
if (ampBindInitData) {
......@@ -424,6 +428,7 @@ export async function renderToHTML(
let html = renderDocument(Document, {
...renderOpts,
dangerousAsPath: router.asPath,
dataManagerData,
ampMode,
props,
......
......@@ -20,7 +20,12 @@ export function isBlockedPage(pathname: string): boolean {
}
export function cleanAmpPath(pathname: string): string {
return (pathname || '')
.replace(/\.amp$/, '')
.replace(/\index$/, '')
if (pathname.match(/\?amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/\?amp=(y|yes|true|1)/, '?')
}
if (pathname.match(/&amp=(y|yes|true|1)/)) {
pathname = pathname.replace(/\?amp=(y|yes|true|1)/, '')
}
pathname = pathname.replace(/\?$/, '')
return pathname
}
......@@ -59,9 +59,12 @@ export default function getBaseWebpackConfig (dir: string, {dev = false, debug =
'next/router': 'next/dist/client/router.js',
'next/config': 'next-server/dist/lib/runtime-config.js',
'next/dynamic': 'next-server/dist/lib/dynamic.js',
...(config.experimental.amp ? {} : {
'next/amp': 'you-must-enable-experimental-amp',
}),
next: NEXT_PROJECT_ROOT,
[PAGES_DIR_ALIAS]: path.join(dir, 'pages'),
[DOT_NEXT_ALIAS]: distDir
[DOT_NEXT_ALIAS]: distDir,
},
mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main']
}
......
/* eslint-disable */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { cleanAmpPath } from 'next-server/dist/server/utils'
import { htmlEscapeJsonString } from '../server/htmlescape'
import flush from 'styled-jsx/server'
......@@ -9,6 +9,11 @@ import {
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
} from 'next-server/constants'
function getAmpPath(ampPath, asPath) {
return ampPath ? ampPath
: `${asPath}${asPath.includes('?') ? '&' : '?'}amp=1`
}
export default class Document extends Component {
static childContextTypes = {
_documentProps: PropTypes.any,
......@@ -154,6 +159,7 @@ export class Head extends Component {
ampPath,
assetPrefix,
__NEXT_DATA__,
dangerousAsPath,
} = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId, dynamicBuildId } = __NEXT_DATA__
......@@ -218,8 +224,8 @@ export class Head extends Component {
name="viewport"
content="width=device-width,minimum-scale=1,initial-scale=1"
/>
<link rel="canonical" href={cleanAmpPath(page)} />
{isDirtyAmp && <link rel="amphtml" href={ampPath ? ampPath : `${page}?amp=1`} />}
<link rel="canonical" href={cleanAmpPath(dangerousAsPath)} />
{isDirtyAmp && <link rel="amphtml" href={getAmpPath(ampPath, dangerousAsPath)} />}
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link
rel="preload"
......@@ -258,7 +264,7 @@ export class Head extends Component {
)}
{!amphtml && (
<>
{hasAmp && <link rel="amphtml" href={ampPath ? ampPath : `${page}?amp=1`} />}
{hasAmp && <link rel="amphtml" href={getAmpPath(ampPath, dangerousAsPath)} />}
{page !== '/_error' && (
<link
rel="preload"
......
module.exports = {
// exportPathMap
experimental: {
amp: true
}
}
......@@ -35,7 +35,12 @@ describe('AMP Validation on Export', () => {
})
it('should disable dirty AMP with noDirtyAmp set', async () => {
nextConfig.replace(`// exportPathMap`, `experimental: { noDirtyAmp: true } `)
nextConfig.replace(/experimental:[\w\W]*?}/, `
experimental: {
amp: true,
noDirtyAmp: true
}
`)
await nextExport(appDir, { outdir: outDir })
const ampOnly = ['first', 'second', 'third']
await Promise.all(ampOnly.map(async page => {
......
module.exports = {
experimental: {
amp: true
}
}
......@@ -4,5 +4,8 @@ module.exports = {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
experimental: {
amp: true
},
lambdas: true
}
......@@ -50,6 +50,17 @@ describe('Serverless', () => {
expect(html).toMatch(/ampproject\.org/)
})
it('should have correct amphtml rel link', async () => {
const html = await renderViaHTTP(appPort, '/amp')
expect(html).toMatch(/Hi Im an AMP page/)
expect(html).toMatch(/rel="amphtml" href="\/amp\?amp=1"/)
})
it('should have correct canonical link', async () => {
const html = await renderViaHTTP(appPort, '/amp?amp=1')
expect(html).toMatch(/rel="canonical" href="\/amp"/)
})
it('should render correctly when importing isomorphic-unfetch', async () => {
const url = `http://localhost:${appPort}/fetch`
const res = await fetch(url)
......
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