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'
const isAmp = useAmp() }
return ( export default () => {
<div> const isAmp = useAmp()
<Head>
<title>The Dog</title> return (
</Head> <div>
<h1>The Dog (Hybrid AMP Page)</h1> <Head>
<Byline author='Meow Meow Fuzzyface' /> <title>The Dog</title>
<p> </Head>
<a href={isAmp ? '/dog' : '/dog?amp=1'}> <h1>The Dog (Hybrid AMP Page)</h1>
{isAmp ? 'View Non-AMP' : 'View AMP'} Version <Byline author='Meow Meow Fuzzyface' />
</a> <p>
</p> <a href={isAmp ? '/dog' : '/dog?amp=1'}>
<p className='caption'>Woooooooooooof</p> {isAmp ? 'View Non-AMP' : 'View AMP'} Version
<p> </a>
Wafer donut candy soufflé{' '} </p>
<a href={isAmp ? '/?amp=1' : '/'}>lemon drops</a> icing. Marzipan <p className='caption'>Woooooooooooof</p>
gummi bears pie danish lollipop pudding powder gummi bears sweet. Pie <p>
sweet roll sweet roll topping chocolate bar dragée pudding chocolate Wafer donut candy soufflé{' '}
cake. Croissant sweet chocolate bar cheesecake candy canes. Tootsie <a href={isAmp ? '/?amp=1' : '/'}>lemon drops</a> icing. Marzipan gummi
roll icing macaroon bonbon cupcake apple pie candy canes biscuit candy bears pie danish lollipop pudding powder gummi bears sweet. Pie sweet
canes. Jujubes jelly liquorice toffee gingerbread. Candy tootsie roll roll sweet roll topping chocolate bar dragée pudding chocolate cake.
macaroon chocolate bar icing sugar plum pie. Icing gummies chocolate Croissant sweet chocolate bar cheesecake candy canes. Tootsie roll icing
bar chocolate marzipan bonbon cookie chocolate tart. Caramels danish macaroon bonbon cupcake apple pie candy canes biscuit candy canes.
halvah croissant. Cheesecake cookie tootsie roll ice cream. Powder Jujubes jelly liquorice toffee gingerbread. Candy tootsie roll macaroon
dessert carrot cake muffin tiramisu lemon drops liquorice topping chocolate bar icing sugar plum pie. Icing gummies chocolate bar
brownie. Soufflé chocolate cake croissant cupcake jelly. chocolate marzipan bonbon cookie chocolate tart. Caramels danish halvah
</p> croissant. Cheesecake cookie tootsie roll ice cream. Powder dessert
<p> carrot cake muffin tiramisu lemon drops liquorice topping brownie.
Muffin gummies dessert cheesecake candy canes. Candy canes danish Soufflé chocolate cake croissant cupcake jelly.
cotton candy tart dessert powder bear claw marshmallow. Muffin </p>
chocolate marshmallow danish. Chocolate bar biscuit cake tiramisu. <p>
Topping sweet brownie jujubes powder marzipan. Croissant wafer bonbon Muffin gummies dessert cheesecake candy canes. Candy canes danish cotton
chupa chups cake cake marzipan caramels jujubes. Cupcake cheesecake candy tart dessert powder bear claw marshmallow. Muffin chocolate
sweet roll marshmallow lollipop danish jujubes jelly icing. Apple pie marshmallow danish. Chocolate bar biscuit cake tiramisu. Topping sweet
chupa chups lollipop jelly-o cheesecake jelly beans cake dessert. brownie jujubes powder marzipan. Croissant wafer bonbon chupa chups cake
Tootsie roll tootsie roll bonbon pastry croissant gummi bears cake cake marzipan caramels jujubes. Cupcake cheesecake sweet roll
cake. Fruitcake sugar plum halvah gingerbread cookie pastry chupa marshmallow lollipop danish jujubes jelly icing. Apple pie chupa chups
chups wafer lemon drops. Marshmallow liquorice oat cake lollipop. lollipop jelly-o cheesecake jelly beans cake dessert. Tootsie roll
Lemon drops oat cake halvah liquorice danish powder cupcake soufflé. tootsie roll bonbon pastry croissant gummi bears cake cake. Fruitcake
Cake tart topping jelly-o tart sugar plum. Chocolate bar cookie wafer sugar plum halvah gingerbread cookie pastry chupa chups wafer lemon
tootsie roll candy cotton candy toffee pie donut. drops. Marshmallow liquorice oat cake lollipop. Lemon drops oat cake
</p> halvah liquorice danish powder cupcake soufflé. Cake tart topping
<p> jelly-o tart sugar plum. Chocolate bar cookie wafer tootsie roll candy
Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw cotton candy toffee pie donut.
lemon drops marzipan candy bonbon cupcake powder. Candy canes </p>
cheesecake bear claw pastry cake donut jujubes. Icing tart jelly-o <p>
soufflé bonbon apple pie. Cheesecake pie chupa chups toffee powder. Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw
Bonbon lemon drops carrot cake pudding candy halvah cheesecake lemon drops marzipan candy bonbon cupcake powder. Candy canes cheesecake
lollipop cupcake. Pudding marshmallow fruitcake. Gummi bears bonbon bear claw pastry cake donut jujubes. Icing tart jelly-o soufflé bonbon
chupa chups lemon drops. Wafer dessert gummies gummi bears biscuit apple pie. Cheesecake pie chupa chups toffee powder. Bonbon lemon drops
donut tiramisu gummi bears brownie. Tootsie roll liquorice bonbon carrot cake pudding candy halvah cheesecake lollipop cupcake. Pudding
cookie. Sesame snaps chocolate bar cake croissant chupa chups marshmallow fruitcake. Gummi bears bonbon chupa chups lemon drops. Wafer
cheesecake gingerbread tiramisu jelly. Cheesecake ice cream muffin dessert gummies gummi bears biscuit donut tiramisu gummi bears brownie.
lollipop gummies. Sesame snaps jelly beans sweet bear claw tart. Tootsie roll liquorice bonbon cookie. Sesame snaps chocolate bar cake
</p> croissant chupa chups cheesecake gingerbread tiramisu jelly. Cheesecake
<p> ice cream muffin lollipop gummies. Sesame snaps jelly beans sweet bear
Sweet topping chupa chups chocolate cake jelly-o liquorice danish. claw tart.
Pastry jelly beans apple pie dessert pastry lemon drops marzipan </p>
gummies. Jelly beans macaroon bear claw cotton candy. Toffee sweet <p>
lollipop toffee oat cake. Jelly-o oat cake fruitcake chocolate bar Sweet topping chupa chups chocolate cake jelly-o liquorice danish.
sweet. Lemon drops gummies chocolate cake lollipop bear claw croissant Pastry jelly beans apple pie dessert pastry lemon drops marzipan
danish icing. Chocolate bar donut brownie chocolate cake lemon drops gummies. Jelly beans macaroon bear claw cotton candy. Toffee sweet
chocolate bar. Cake fruitcake pudding chocolate apple pie. Brownie lollipop toffee oat cake. Jelly-o oat cake fruitcake chocolate bar
tiramisu chocolate macaroon lemon drops wafer soufflé jujubes icing. sweet. Lemon drops gummies chocolate cake lollipop bear claw croissant
Cheesecake tiramisu cake macaroon tart lollipop donut. Gummi bears danish icing. Chocolate bar donut brownie chocolate cake lemon drops
dragée pudding bear claw. Muffin cake cupcake candy canes. Soufflé chocolate bar. Cake fruitcake pudding chocolate apple pie. Brownie
candy canes biscuit. Macaroon gummies danish. tiramisu chocolate macaroon lemon drops wafer soufflé jujubes icing.
</p> Cheesecake tiramisu cake macaroon tart lollipop donut. Gummi bears
<p> dragée pudding bear claw. Muffin cake cupcake candy canes. Soufflé candy
Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice canes biscuit. Macaroon gummies danish.
cream candy canes powder wafer. Chocolate sesame snaps oat cake dragée </p>
cheesecake. Sesame snaps marshmallow topping liquorice cookie <p>
marshmallow. Liquorice pudding chocolate bar. Cake powder brownie Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice cream
fruitcake. Carrot cake dessert marzipan sugar plum cupcake cheesecake candy canes powder wafer. Chocolate sesame snaps oat cake dragée
pastry. Apple pie macaroon ice cream fruitcake apple pie cookie. cheesecake. Sesame snaps marshmallow topping liquorice cookie
Tootsie roll ice cream oat cake cheesecake donut cheesecake bear claw. marshmallow. Liquorice pudding chocolate bar. Cake powder brownie
Sesame snaps marzipan jelly beans chocolate tootsie roll. Chocolate fruitcake. Carrot cake dessert marzipan sugar plum cupcake cheesecake
bar donut dragée ice cream biscuit. Pie candy canes muffin candy canes pastry. Apple pie macaroon ice cream fruitcake apple pie cookie. Tootsie
ice cream tiramisu. roll ice cream oat cake cheesecake donut cheesecake bear claw. Sesame
</p> snaps marzipan jelly beans chocolate tootsie roll. Chocolate bar donut
</div> dragée ice cream biscuit. Pie candy canes muffin candy canes ice cream
) tiramisu.
}, </p>
{ hybrid: true } </div>
) )
}
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,46 +1932,45 @@ export default Page ...@@ -1932,46 +1932,45 @@ 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 default withAmp( export const config = { amp: true }
function AboutPage(props) {
return ( export default function AboutPage(props) {
<div> return (
<h3>My AMP Page</h3> <div>
{useAmp() ? ( <h3>My AMP Page</h3>
<amp-img {useAmp() ? (
width="300" <amp-img
height="300" width="300"
src="/my-img.jpg" height="300"
alt="a cool image" src="/my-img.jpg"
layout="responsive" alt="a cool image"
/> layout="responsive"
) : ( />
<img width="300" height="300" src="/my-img.jpg" alt="a cool image" /> ) : (
)} <img width="300" height="300" src="/my-img.jpg" alt="a cool image" />
</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' }
() => {
const isAmp = useAmp() export default () => {
return `Hello ${isAmp ? 'AMP' : 'others'}` const isAmp = useAmp()
}, 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' }
() => {
const isAmp = useAmp() export default () => {
return `Hello ${isAmp ? 'AMP' : 'others'}` const isAmp = useAmp()
}, 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