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

Add export const config support and make withAmp a no-op (#7525)

* Add export const config support and make withAmp a no-op

* Use babel plugin for PageConfig

* Fix serverless-loader exports

* Add backwards compatibility for withAmp
parent a4d6d86d
import Head from 'next/head' import Head from 'next/head'
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
import Byline from '../components/Byline' import Byline from '../components/Byline'
export default withAmp( export const config = {
() => { amp: 'hybrid'
}
export default () => {
const isAmp = useAmp() const isAmp = useAmp()
return ( return (
...@@ -21,45 +24,45 @@ export default withAmp( ...@@ -21,45 +24,45 @@ export default withAmp(
<p className='caption'>Woooooooooooof</p> <p className='caption'>Woooooooooooof</p>
<p> <p>
Wafer donut candy soufflé{' '} Wafer donut candy soufflé{' '}
<a href={isAmp ? '/?amp=1' : '/'}>lemon drops</a> icing. Marzipan <a href={isAmp ? '/?amp=1' : '/'}>lemon drops</a> icing. Marzipan gummi
gummi bears pie danish lollipop pudding powder gummi bears sweet. Pie bears pie danish lollipop pudding powder gummi bears sweet. Pie sweet
sweet roll sweet roll topping chocolate bar dragée pudding chocolate roll sweet roll topping chocolate bar dragée pudding chocolate cake.
cake. Croissant sweet chocolate bar cheesecake candy canes. Tootsie Croissant sweet chocolate bar cheesecake candy canes. Tootsie roll icing
roll icing macaroon bonbon cupcake apple pie candy canes biscuit candy macaroon bonbon cupcake apple pie candy canes biscuit candy canes.
canes. Jujubes jelly liquorice toffee gingerbread. Candy tootsie roll Jujubes jelly liquorice toffee gingerbread. Candy tootsie roll macaroon
macaroon chocolate bar icing sugar plum pie. Icing gummies chocolate chocolate bar icing sugar plum pie. Icing gummies chocolate bar
bar chocolate marzipan bonbon cookie chocolate tart. Caramels danish chocolate marzipan bonbon cookie chocolate tart. Caramels danish halvah
halvah croissant. Cheesecake cookie tootsie roll ice cream. Powder croissant. Cheesecake cookie tootsie roll ice cream. Powder dessert
dessert carrot cake muffin tiramisu lemon drops liquorice topping carrot cake muffin tiramisu lemon drops liquorice topping brownie.
brownie. Soufflé chocolate cake croissant cupcake jelly. Soufflé chocolate cake croissant cupcake jelly.
</p> </p>
<p> <p>
Muffin gummies dessert cheesecake candy canes. Candy canes danish Muffin gummies dessert cheesecake candy canes. Candy canes danish cotton
cotton candy tart dessert powder bear claw marshmallow. Muffin candy tart dessert powder bear claw marshmallow. Muffin chocolate
chocolate marshmallow danish. Chocolate bar biscuit cake tiramisu. marshmallow danish. Chocolate bar biscuit cake tiramisu. Topping sweet
Topping sweet brownie jujubes powder marzipan. Croissant wafer bonbon brownie jujubes powder marzipan. Croissant wafer bonbon chupa chups cake
chupa chups cake cake marzipan caramels jujubes. Cupcake cheesecake cake marzipan caramels jujubes. Cupcake cheesecake sweet roll
sweet roll marshmallow lollipop danish jujubes jelly icing. Apple pie marshmallow lollipop danish jujubes jelly icing. Apple pie chupa chups
chupa chups lollipop jelly-o cheesecake jelly beans cake dessert. lollipop jelly-o cheesecake jelly beans cake dessert. Tootsie roll
Tootsie roll tootsie roll bonbon pastry croissant gummi bears cake tootsie roll bonbon pastry croissant gummi bears cake cake. Fruitcake
cake. Fruitcake sugar plum halvah gingerbread cookie pastry chupa sugar plum halvah gingerbread cookie pastry chupa chups wafer lemon
chups wafer lemon drops. Marshmallow liquorice oat cake lollipop. drops. Marshmallow liquorice oat cake lollipop. Lemon drops oat cake
Lemon drops oat cake halvah liquorice danish powder cupcake soufflé. halvah liquorice danish powder cupcake soufflé. Cake tart topping
Cake tart topping jelly-o tart sugar plum. Chocolate bar cookie wafer jelly-o tart sugar plum. Chocolate bar cookie wafer tootsie roll candy
tootsie roll candy cotton candy toffee pie donut. cotton candy toffee pie donut.
</p> </p>
<p> <p>
Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw
lemon drops marzipan candy bonbon cupcake powder. Candy canes lemon drops marzipan candy bonbon cupcake powder. Candy canes cheesecake
cheesecake bear claw pastry cake donut jujubes. Icing tart jelly-o bear claw pastry cake donut jujubes. Icing tart jelly-o soufflé bonbon
soufflé bonbon apple pie. Cheesecake pie chupa chups toffee powder. apple pie. Cheesecake pie chupa chups toffee powder. Bonbon lemon drops
Bonbon lemon drops carrot cake pudding candy halvah cheesecake carrot cake pudding candy halvah cheesecake lollipop cupcake. Pudding
lollipop cupcake. Pudding marshmallow fruitcake. Gummi bears bonbon marshmallow fruitcake. Gummi bears bonbon chupa chups lemon drops. Wafer
chupa chups lemon drops. Wafer dessert gummies gummi bears biscuit dessert gummies gummi bears biscuit donut tiramisu gummi bears brownie.
donut tiramisu gummi bears brownie. Tootsie roll liquorice bonbon Tootsie roll liquorice bonbon cookie. Sesame snaps chocolate bar cake
cookie. Sesame snaps chocolate bar cake croissant chupa chups croissant chupa chups cheesecake gingerbread tiramisu jelly. Cheesecake
cheesecake gingerbread tiramisu jelly. Cheesecake ice cream muffin ice cream muffin lollipop gummies. Sesame snaps jelly beans sweet bear
lollipop gummies. Sesame snaps jelly beans sweet bear claw tart. claw tart.
</p> </p>
<p> <p>
Sweet topping chupa chups chocolate cake jelly-o liquorice danish. Sweet topping chupa chups chocolate cake jelly-o liquorice danish.
...@@ -71,23 +74,21 @@ export default withAmp( ...@@ -71,23 +74,21 @@ export default withAmp(
chocolate bar. Cake fruitcake pudding chocolate apple pie. Brownie chocolate bar. Cake fruitcake pudding chocolate apple pie. Brownie
tiramisu chocolate macaroon lemon drops wafer soufflé jujubes icing. tiramisu chocolate macaroon lemon drops wafer soufflé jujubes icing.
Cheesecake tiramisu cake macaroon tart lollipop donut. Gummi bears Cheesecake tiramisu cake macaroon tart lollipop donut. Gummi bears
dragée pudding bear claw. Muffin cake cupcake candy canes. Soufflé dragée pudding bear claw. Muffin cake cupcake candy canes. Soufflé candy
candy canes biscuit. Macaroon gummies danish. canes biscuit. Macaroon gummies danish.
</p> </p>
<p> <p>
Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice cream
cream candy canes powder wafer. Chocolate sesame snaps oat cake dragée candy canes powder wafer. Chocolate sesame snaps oat cake dragée
cheesecake. Sesame snaps marshmallow topping liquorice cookie cheesecake. Sesame snaps marshmallow topping liquorice cookie
marshmallow. Liquorice pudding chocolate bar. Cake powder brownie marshmallow. Liquorice pudding chocolate bar. Cake powder brownie
fruitcake. Carrot cake dessert marzipan sugar plum cupcake cheesecake fruitcake. Carrot cake dessert marzipan sugar plum cupcake cheesecake
pastry. Apple pie macaroon ice cream fruitcake apple pie cookie. pastry. Apple pie macaroon ice cream fruitcake apple pie cookie. Tootsie
Tootsie roll ice cream oat cake cheesecake donut cheesecake bear claw. roll ice cream oat cake cheesecake donut cheesecake bear claw. Sesame
Sesame snaps marzipan jelly beans chocolate tootsie roll. Chocolate snaps marzipan jelly beans chocolate tootsie roll. Chocolate bar donut
bar donut dragée ice cream biscuit. Pie candy canes muffin candy canes dragée ice cream biscuit. Pie candy canes muffin candy canes ice cream
ice cream tiramisu. tiramisu.
</p> </p>
</div> </div>
) )
}, }
{ hybrid: true }
)
import Head from 'next/head' import Head from 'next/head'
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
import Layout from '../components/Layout' import Layout from '../components/Layout'
import Byline from '../components/Byline' import Byline from '../components/Byline'
export default withAmp(() => { export const config = {
amp: true
}
export default () => {
const isAmp = useAmp() const isAmp = useAmp()
return ( return (
...@@ -214,4 +218,4 @@ export default withAmp(() => { ...@@ -214,4 +218,4 @@ export default withAmp(() => {
`}</style> `}</style>
</Layout> </Layout>
) )
}) }
...@@ -15,6 +15,9 @@ export function useAmp() { ...@@ -15,6 +15,9 @@ export function useAmp() {
return isAmp(ampMode) // && ampMode.hasQuery return isAmp(ampMode) // && ampMode.hasQuery
} }
/**
* @deprecated This is no longer required, use export const config = { amp: true }
*/
export function withAmp(Component: any, { hybrid = false } = {}): any { export function withAmp(Component: any, { hybrid = false } = {}): any {
function WithAmpWrapper(props = {}) { function WithAmpWrapper(props = {}) {
const ampMode = React.useContext(AmpModeContext) const ampMode = React.useContext(AmpModeContext)
......
...@@ -12,8 +12,13 @@ export function interopDefault(mod: any) { ...@@ -12,8 +12,13 @@ export function interopDefault(mod: any) {
return mod.default || mod return mod.default || mod
} }
export interface IPageConfig {
amp?: boolean | 'hybrid'
}
export type LoadComponentsReturnType = { export type LoadComponentsReturnType = {
Component: any Component: any
PageConfig: IPageConfig
buildManifest?: any buildManifest?: any
reactLoadableManifest?: any reactLoadableManifest?: any
Document?: any Document?: any
...@@ -29,7 +34,7 @@ export async function loadComponents( ...@@ -29,7 +34,7 @@ export async function loadComponents(
): Promise<LoadComponentsReturnType> { ): Promise<LoadComponentsReturnType> {
if (serverless) { if (serverless) {
const Component = await requirePage(pathname, distDir, serverless) const Component = await requirePage(pathname, distDir, serverless)
return { Component } return { Component, PageConfig: Component.config || {} }
} }
const documentPath = join( const documentPath = join(
distDir, distDir,
...@@ -51,6 +56,8 @@ export async function loadComponents( ...@@ -51,6 +56,8 @@ export async function loadComponents(
const DocumentMod = require(documentPath) const DocumentMod = require(documentPath)
const { middleware: DocumentMiddleware } = DocumentMod const { middleware: DocumentMiddleware } = DocumentMod
const ComponentMod = requirePage(pathname, distDir, serverless)
const [ const [
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
...@@ -60,17 +67,18 @@ export async function loadComponents( ...@@ -60,17 +67,18 @@ export async function loadComponents(
] = await Promise.all([ ] = await Promise.all([
require(join(distDir, BUILD_MANIFEST)), require(join(distDir, BUILD_MANIFEST)),
require(join(distDir, REACT_LOADABLE_MANIFEST)), require(join(distDir, REACT_LOADABLE_MANIFEST)),
interopDefault(requirePage(pathname, distDir, serverless)), interopDefault(ComponentMod),
interopDefault(DocumentMod), interopDefault(DocumentMod),
interopDefault(require(appPath)), interopDefault(require(appPath)),
]) ])
return { return {
buildManifest, App,
reactLoadableManifest,
Component,
Document, Document,
Component,
buildManifest,
DocumentMiddleware, DocumentMiddleware,
App, reactLoadableManifest,
PageConfig: ComponentMod.config || {},
} }
} }
...@@ -468,7 +468,11 @@ export default class Server { ...@@ -468,7 +468,11 @@ export default class Server {
return result.Component.renderReqToHTML(req, res) return result.Component.renderReqToHTML(req, res)
} }
return renderToHTML(req, res, pathname, query, { ...result, ...opts }) return renderToHTML(req, res, pathname, query, {
...result,
...opts,
PageConfig: result.PageConfig,
})
} }
public renderToHTML( public renderToHTML(
......
...@@ -33,6 +33,7 @@ import { getPageFiles, BuildManifest } from './get-page-files' ...@@ -33,6 +33,7 @@ import { getPageFiles, BuildManifest } from './get-page-files'
import { AmpModeContext } from '../lib/amphtml-context' import { AmpModeContext } from '../lib/amphtml-context'
import optimizeAmp from './optimize-amp' import optimizeAmp from './optimize-amp'
import { isAmp } from '../lib/amp' import { isAmp } from '../lib/amp'
import { IPageConfig } from './load-components'
function noRouter() { function noRouter() {
const message = const message =
...@@ -140,6 +141,7 @@ type RenderOpts = { ...@@ -140,6 +141,7 @@ type RenderOpts = {
dataOnly?: boolean dataOnly?: boolean
buildManifest: BuildManifest buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest reactLoadableManifest: ReactLoadableManifest
PageConfig: IPageConfig
Component: React.ComponentType Component: React.ComponentType
Document: DocumentType Document: DocumentType
DocumentMiddleware: (ctx: NextPageContext) => void DocumentMiddleware: (ctx: NextPageContext) => void
...@@ -244,6 +246,7 @@ export async function renderToHTML( ...@@ -244,6 +246,7 @@ export async function renderToHTML(
ampPath = '', ampPath = '',
App, App,
Document, Document,
PageConfig,
DocumentMiddleware, DocumentMiddleware,
Component, Component,
buildManifest, buildManifest,
...@@ -354,8 +357,9 @@ export async function renderToHTML( ...@@ -354,8 +357,9 @@ export async function renderToHTML(
let renderPage: RenderPage let renderPage: RenderPage
const ampMode = { const ampMode = {
enabled: false, enabled: Boolean(PageConfig.amp),
hasQuery: Boolean(query.amp), hasQuery: Boolean(query.amp),
hybrid: PageConfig.amp === 'hybrid',
} }
if (ampBindInitData) { if (ampBindInitData) {
......
...@@ -1932,27 +1932,28 @@ export default Page ...@@ -1932,27 +1932,28 @@ export default Page
### Enabling AMP Support ### Enabling AMP Support
To enable AMP support for a page, first enable experimental AMP support in your `next.config.js` and then import `withAmp` from `next/amp` and wrap your page's component in it. To enable AMP support for a page, add `export const config = { amp: true }` to your page.
### AMP First Page ### AMP First Page
```js ```js
// pages/about.js // pages/about.js
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(function AboutPage(props) { export default function AboutPage(props) {
return <h3>My AMP About Page!</h3> return <h3>My AMP About Page!</h3>
}) }
``` ```
### Hybrid AMP Page ### Hybrid AMP Page
```js ```js
// pages/hybrid-about.js // pages/hybrid-about.js
import { withAmp, useAmp } from 'next/amp' import { useAmp } from 'next/amp'
export const config = { amp: true }
export default withAmp( export default function AboutPage(props) {
function AboutPage(props) {
return ( return (
<div> <div>
<h3>My AMP Page</h3> <h3>My AMP Page</h3>
...@@ -1969,9 +1970,7 @@ export default withAmp( ...@@ -1969,9 +1970,7 @@ export default withAmp(
)} )}
</div> </div>
) )
}, }
{ hybrid: true }
)
``` ```
### AMP Page Modes ### AMP Page Modes
...@@ -1982,11 +1981,11 @@ AMP pages can specify two modes: ...@@ -1982,11 +1981,11 @@ AMP pages can specify two modes:
- Pages have no Next.js or React client-side runtime - Pages have no Next.js or React client-side runtime
- Pages are automatically optimized with [AMP Optimizer](https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer), an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%) - Pages are automatically optimized with [AMP Optimizer](https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer), an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%)
- Pages have a user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page - Pages have a user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page
- Opt-in via `withAmp(Component)` - Opt-in via `export const config = { amp: true }`
- Hybrid - Hybrid
- Pages are able to be rendered as traditional HTML (default) and AMP HTML (by adding `?amp=1` to the URL) - Pages are able to be rendered as traditional HTML (default) and AMP HTML (by adding `?amp=1` to the URL)
- The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines - The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines
- Opt-in via `withAmp(Component, { hybrid: true })` - Opt-in via `export const config = { amp: 'hybrid' }`
- Able to differentiate between modes using `useAmp` from `next/amp` - Able to differentiate between modes using `useAmp` from `next/amp`
Both of these page modes provide a consistently fast experience for users accessing pages through search engines. Both of these page modes provide a consistently fast experience for users accessing pages through search engines.
...@@ -2013,9 +2012,10 @@ The AMP community provides [many components](https://amp.dev/documentation/compo ...@@ -2013,9 +2012,10 @@ The AMP community provides [many components](https://amp.dev/documentation/compo
```js ```js
// pages/hello.js // pages/hello.js
import Head from 'next/head' import Head from 'next/head'
import { withAmp } from 'next/amp'
export default withAmp(function MyAmpPage() { export const config = { amp: true }
export default function MyAmpPage() {
return ( return (
<div> <div>
<Head> <Head>
...@@ -2038,7 +2038,7 @@ export default withAmp(function MyAmpPage() { ...@@ -2038,7 +2038,7 @@ export default withAmp(function MyAmpPage() {
</amp-timeago> </amp-timeago>
</div> </div>
) )
}) }
``` ```
### AMP Validation ### AMP Validation
......
import { PluginObj } from '@babel/core'
import { NodePath } from '@babel/traverse'
import * as BabelTypes from '@babel/types'
let idx = 0
export default function({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj<{
insertedDrop?: boolean
hasAmp?: boolean
}> {
return {
visitor: {
Program: {
enter(path, state) {
path.traverse(
{
ImportDeclaration(
path: NodePath<BabelTypes.ImportDeclaration>,
state
) {
const source = path.node.source.value
if (source !== 'next/amp') return
state.hasAmp = true
},
},
state
)
},
},
CallExpression(path: NodePath<BabelTypes.CallExpression>, state) {
if (!state.hasAmp || state.insertedDrop) return
// @ts-ignore
if (path.node.callee.name !== 'withAmp') return
if (path.node.arguments.length > 1) {
if (!t.isObjectExpression(path.node.arguments[1])) return
// @ts-ignore
const options: BabelTypes.ObjectExpression = path.node.arguments[1]
// make sure it isn't a hybrid page e.g. hybrid: true
if (
options.properties.some(
(prop: any): boolean => {
if (!t.isObjectProperty(prop)) return false
if (
prop.key.name !== 'hybrid' ||
!t.isBooleanLiteral(prop.value)
) {
return false
}
// found hybrid: true
return Boolean(prop.value.value)
}
)
) {
return
}
}
// use random number and an increment to make sure HMR still updates
idx++
state.insertedDrop = true
path.replaceWith(
t.expressionStatement(
t.stringLiteral(
`throw new Error('__NEXT_DROP_CLIENT_FILE__' + ${Math.random() +
idx})`
)
)
)
},
},
}
}
import { PluginObj } from '@babel/core'
import { NodePath } from '@babel/traverse'
import * as BabelTypes from '@babel/types'
interface PageConfig {
amp?: boolean | 'hybrid'
}
function replacePath(path: any, t: typeof BabelTypes) {
path.parentPath.replaceWith(
t.program(
[
t.variableDeclaration('const', [
t.variableDeclarator(
t.identifier('config'),
t.assignmentExpression(
'=',
t.identifier('no'), // this can't be empty but is required
t.stringLiteral(`__NEXT_DROP_CLIENT_FILE__ ${Date.now()}`)
)
),
]),
],
[]
)
)
}
export default function nextPageConfig({
types: t,
}: {
types: typeof BabelTypes
}): PluginObj<{
insertedDrop?: boolean
hasAmp?: boolean
}> {
return {
visitor: {
Program: {
enter(path, state: any) {
path.traverse(
{
ExportNamedDeclaration(
path: NodePath<BabelTypes.ExportNamedDeclaration>,
state: any
) {
if (
state.replaced ||
!path.node.declaration ||
!(path.node.declaration as any).declarations
)
return
const { declarations } = path.node.declaration as any
const config: PageConfig = {}
for (const declaration of declarations) {
if (declaration.id.name !== 'config') continue
for (const prop of declaration.init.properties) {
const { name } = prop.key
if (name === 'amp') config.amp = prop.value.value
}
}
if (config.amp === true) {
replacePath(path, t)
state.replaced = true
}
},
CallExpression(path: NodePath<BabelTypes.CallExpression>, state) {
// @ts-ignore
if (state.replaced || path.node.callee.name !== 'withAmp')
return
if (path.node.arguments.length > 1) {
if (!t.isObjectExpression(path.node.arguments[1])) return
// @ts-ignore
const options: BabelTypes.ObjectExpression =
path.node.arguments[1]
// make sure it isn't a hybrid page e.g. hybrid: true
if (
options.properties.some(
(prop: any): boolean => {
if (!t.isObjectProperty(prop)) return false
if (
prop.key.name !== 'hybrid' ||
!t.isBooleanLiteral(prop.value)
) {
return false
}
// found hybrid: true
return Boolean(prop.value.value)
}
)
) {
return
}
}
// use random number and an increment to make sure HMR still updates
replacePath(path, t)
state.replaced = true
},
},
state
)
},
},
},
}
}
...@@ -77,13 +77,13 @@ module.exports = babelLoader.custom(babel => { ...@@ -77,13 +77,13 @@ module.exports = babelLoader.custom(babel => {
options.presets = [...options.presets, presetItem] options.presets = [...options.presets, presetItem]
} }
if (!isServer && source.indexOf('next/amp')) { if (!isServer && filename.indexOf('pages') !== -1) {
const dropClientPlugin = babel.createConfigItem( const pageConfigPlugin = babel.createConfigItem(
[require('../../babel/plugins/next-drop-client-page'), {}], [require('../../babel/plugins/next-page-config')],
{ type: 'plugin' } { type: 'plugin' }
) )
options.plugins = options.plugins || [] options.plugins = options.plugins || []
options.plugins.push(dropClientPlugin) options.plugins.push(pageConfigPlugin)
} }
if (isServer && source.indexOf('next/data') !== -1) { if (isServer && source.indexOf('next/data') !== -1) {
......
...@@ -51,8 +51,10 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -51,8 +51,10 @@ const nextServerlessLoader: loader.Loader = function() {
import Document from '${absoluteDocumentPath}'; import Document from '${absoluteDocumentPath}';
import Error from '${absoluteErrorPath}'; import Error from '${absoluteErrorPath}';
import App from '${absoluteAppPath}'; import App from '${absoluteAppPath}';
import Component from '${absolutePagePath}'; import * as ComponentInfo from '${absolutePagePath}';
const Component = ComponentInfo.default
export default Component export default Component
export const PageConfig = ComponentInfo['confi' + 'g'] || {}
export const _app = App export const _app = App
export async function renderReqToHTML(req, res, fromExport) { export async function renderReqToHTML(req, res, fromExport) {
const options = { const options = {
...@@ -71,6 +73,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -71,6 +73,7 @@ const nextServerlessLoader: loader.Loader = function() {
const renderOpts = Object.assign( const renderOpts = Object.assign(
{ {
Component, Component,
PageConfig,
dataOnly: req.headers && (req.headers.accept || '').indexOf('application/amp.bind+json') !== -1, dataOnly: req.headers && (req.headers.accept || '').indexOf('application/amp.bind+json') !== -1,
nextExport: fromExport nextExport: fromExport
}, },
......
...@@ -43,4 +43,11 @@ export type NextPage<P = {}, IP = P> = { ...@@ -43,4 +43,11 @@ export type NextPage<P = {}, IP = P> = {
getInitialProps?(ctx: NextPageContext): Promise<IP> getInitialProps?(ctx: NextPageContext): Promise<IP>
} }
/**
* `Config` type, use it for export const config
*/
export type PageConfig = {
amp?: boolean | 'hybrid'
}
export { NextPageContext, NextComponentType, NextApiResponse, NextApiRequest } export { NextPageContext, NextComponentType, NextApiResponse, NextApiRequest }
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<div> <div>
{/* I show a warning since the amp-video script isn't added */} {/* I show a warning since the amp-video script isn't added */}
<amp-video src='/cats.mp4' height={400} width={800} /> <amp-video src='/cats.mp4' height={400} width={800} />
</div> </div>
)) )
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<div> <div>
{/* I throw an error since <amp-img/> should be used instead */} {/* I throw an error since <amp-img/> should be used instead */}
<img src='/dog.gif' height={400} width={800} /> <img src='/dog.gif' height={400} width={800} />
{/* I show a warning since the amp-video script isn't added */} {/* I show a warning since the amp-video script isn't added */}
<amp-video src='/cats.mp4' height={400} width={800} /> <amp-video src='/cats.mp4' height={400} width={800} />
</div> </div>
)) )
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<div> <div>
{/* I throw an error since <amp-img/> should be used instead */} {/* I throw an error since <amp-img/> should be used instead */}
<img src='/dog.gif' height={400} width={800} /> <img src='/dog.gif' height={400} width={800} />
</div> </div>
)) )
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => <p>Hello AMP!</p>) export default () => <p>Hello AMP!</p>
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => <p>Hello again AMP!</p>) export default () => <p>Hello again AMP!</p>
import { withAmp } from 'next/amp' export const config = { amp: 'hybrid' }
export default withAmp(() => 'I am a hybrid AMP page', { hybrid: true }) export default () => 'I am a hybrid AMP page'
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<div> <div>
<p>Hello world!</p> <p>Hello world!</p>
<style jsx>{` <style jsx>{`
...@@ -9,4 +9,4 @@ export default withAmp(() => ( ...@@ -9,4 +9,4 @@ export default withAmp(() => (
} }
`}</style> `}</style>
</div> </div>
)) )
import Head from 'next/head' import Head from 'next/head'
import { withAmp } from 'next/amp' export const config = { amp: true }
const date = new Date().toJSON() const date = new Date().toJSON()
export default withAmp(() => ( export default () => (
<> <>
<Head> <Head>
<script <script
...@@ -18,4 +18,4 @@ export default withAmp(() => ( ...@@ -18,4 +18,4 @@ export default withAmp(() => (
{date} {date}
</amp-timeago> </amp-timeago>
</> </>
)) )
import Head from 'next/head' import Head from 'next/head'
import { withAmp } from 'next/amp'
export default withAmp(() => ( export const config = { amp: true }
export default () => (
<amp-layout className='abc' layout='responsive' width='1' height='1'> <amp-layout className='abc' layout='responsive' width='1' height='1'>
<Head> <Head>
<meta name='viewport' content='something :p' /> <meta name='viewport' content='something :p' />
</Head> </Head>
<span>Hello World</span> <span>Hello World</span>
</amp-layout> </amp-layout>
)) )
import Head from 'next/head' import Head from 'next/head'
import { withAmp } from 'next/amp'
export default withAmp(() => ( export const config = { amp: true }
export default () => (
<div> <div>
<Head> <Head>
<script src='/im-not-allowed.js' type='text/javascript' /> <script src='/im-not-allowed.js' type='text/javascript' />
...@@ -13,4 +14,4 @@ export default withAmp(() => ( ...@@ -13,4 +14,4 @@ export default withAmp(() => (
</Head> </Head>
<p>We only allow AMP scripts now</p> <p>We only allow AMP scripts now</p>
</div> </div>
)) )
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<> <>
<p>I'm an AMP page!</p> <p>I'm an AMP page!</p>
<span>{new Date().getTime()}</span> <span>{new Date().getTime()}</span>
</> </>
)) )
import { withAmp } from 'next/amp' export const config = { amp: 'hybrid' }
export default withAmp(() => <p>I'm a hybrid AMP page!</p>, { hybrid: true }) export default () => <p>I'm a hybrid AMP page!</p>
import { withAmp } from 'next/amp' export const config = { amp: 'hybrid' }
export default withAmp( export default () => (
() => (
<amp-layout className='abc' layout='responsive' width='1' height='1'> <amp-layout className='abc' layout='responsive' width='1' height='1'>
<span>Hello World</span> <span>Hello World</span>
</amp-layout> </amp-layout>
),
{ hybrid: true }
) )
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
export default withAmp( export const config = { amp: 'hybrid' }
() => {
export default () => {
const isAmp = useAmp() const isAmp = useAmp()
return `Hello ${isAmp ? 'AMP' : 'others'}` return `Hello ${isAmp ? 'AMP' : 'others'}`
}, }
{ hybrid: true }
)
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => ( export default () => (
<div> <div>
<p id='only-amp'>Only AMP for me...</p> <p id='only-amp'>Only AMP for me...</p>
</div> </div>
)) )
import { withAmp } from 'next/amp' export const config = { amp: true }
export default withAmp(() => <p>I'm an AMP page!</p>) export default () => <p>I'm an AMP page!</p>
import Foo from '../components/Foo' import Foo from '../components/Foo'
import Bar from '../components/Bar' import Bar from '../components/Bar'
import { withAmp } from 'next/amp'
export default withAmp(() => ( export const config = { amp: true }
export default () => (
<div> <div>
<Foo /> <Foo />
<Bar /> <Bar />
...@@ -12,4 +13,4 @@ export default withAmp(() => ( ...@@ -12,4 +13,4 @@ export default withAmp(() => (
} }
`}</style> `}</style>
</div> </div>
)) )
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
export default withAmp( export const config = { amp: 'hybrid' }
() => {
export default () => {
const isAmp = useAmp() const isAmp = useAmp()
return `Hello ${isAmp ? 'AMP' : 'others'}` return `Hello ${isAmp ? 'AMP' : 'others'}`
}, }
{ hybrid: true }
)
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
export default withAmp(() => <p>I'm an {useAmp() ? 'AMP' : 'normal'} page</p>, { export const config = { amp: 'hybrid' }
hybrid: true
}) export default () => <p>I'm an {useAmp() ? 'AMP' : 'normal'} page</p>
import { useAmp, withAmp } from 'next/amp' import { useAmp } from 'next/amp'
export default withAmp(() => <p>I'm an {useAmp() ? 'AMP' : 'normal'} page</p>, { export const config = { amp: 'hybrid' }
hybrid: true
}) export default () => <p>I'm an {useAmp() ? 'AMP' : 'normal'} page</p>
import { withAmp } from 'next/amp' export const config = { amp: 'hybrid' }
export default withAmp(() => <p>I'm an AMP page</p>, { hybrid: true }) export default () => <p>I'm an AMP page</p>
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